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,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Collections/ArrayElement.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 System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{Value,nq}")] internal struct ArrayElement<T> { internal T Value; public static implicit operator T(ArrayElement<T> element) { return element.Value; } //NOTE: there is no opposite conversion operator T -> ArrayElement<T> // // that is because it is preferred to update array elements in-place // "elements[i].Value = v" results in much better code than "elements[i] = (ArrayElement<T>)v" // // The reason is that x86 ABI requires that structs must be returned in // a return buffer even if they can fit in a register like this one. // Also since struct contains a reference, the write to the buffer is done with a checked GC barrier // as JIT does not know if the write goes to a stack or a heap location. // Assigning to Value directly easily avoids all this redundancy. [return: NotNullIfNotNull(parameterName: "items")] public static ArrayElement<T>[]? MakeElementArray(T[]? items) { if (items == null) { return null; } var array = new ArrayElement<T>[items.Length]; for (int i = 0; i < items.Length; i++) { array[i].Value = items[i]; } return array; } [return: NotNullIfNotNull(parameterName: "items")] public static T[]? MakeArray(ArrayElement<T>[]? items) { if (items == null) { return null; } var array = new T[items.Length]; for (int i = 0; i < items.Length; i++) { array[i] = items[i].Value; } return array; } } }
// Licensed to the .NET Foundation under one or more 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 System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{Value,nq}")] internal struct ArrayElement<T> { internal T Value; public static implicit operator T(ArrayElement<T> element) { return element.Value; } //NOTE: there is no opposite conversion operator T -> ArrayElement<T> // // that is because it is preferred to update array elements in-place // "elements[i].Value = v" results in much better code than "elements[i] = (ArrayElement<T>)v" // // The reason is that x86 ABI requires that structs must be returned in // a return buffer even if they can fit in a register like this one. // Also since struct contains a reference, the write to the buffer is done with a checked GC barrier // as JIT does not know if the write goes to a stack or a heap location. // Assigning to Value directly easily avoids all this redundancy. [return: NotNullIfNotNull(parameterName: "items")] public static ArrayElement<T>[]? MakeElementArray(T[]? items) { if (items == null) { return null; } var array = new ArrayElement<T>[items.Length]; for (int i = 0; i < items.Length; i++) { array[i].Value = items[i]; } return array; } [return: NotNullIfNotNull(parameterName: "items")] public static T[]? MakeArray(ArrayElement<T>[]? items) { if (items == null) { return null; } var array = new T[items.Length]; for (int i = 0; i < items.Length; i++) { array[i] = items[i].Value; } return array; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/Core/Impl/Options/AbstractRadioButtonViewModel.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.ComponentModel; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged { private readonly AbstractOptionPreviewViewModel _info; internal readonly string Preview; private bool _isChecked; public string Description { get; } public string GroupName { get; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); if (_isChecked) { SetOptionAndUpdatePreview(_info, Preview); } } } public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group) { Description = description; this.Preview = preview; _info = info; this.GroupName = group; SetProperty(ref _isChecked, isChecked); } internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview); } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged { private readonly AbstractOptionPreviewViewModel _info; internal readonly string Preview; private bool _isChecked; public string Description { get; } public string GroupName { get; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); if (_isChecked) { SetOptionAndUpdatePreview(_info, Preview); } } } public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group) { Description = description; this.Preview = preview; _info = info; this.GroupName = group; SetProperty(ref _isChecked, isChecked); } internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Symbols/NonMissingAssemblySymbol.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 Imports System.Collections.Concurrent Imports System.Collections.ObjectModel Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents ''' an assembly that is not missing, i.e. the "real" thing. ''' </summary> Friend MustInherit Class NonMissingAssemblySymbol Inherits AssemblySymbol ''' <summary> ''' This is a cache similar to the one used by MetaImport::GetTypeByName ''' in native compiler. The difference is that native compiler pre-populates ''' the cache when it loads types. Here we are populating the cache only ''' with things we looked for, so that next time we are looking for the same ''' thing, the lookup is fast. This cache also takes care of TypeForwarders. ''' Gives about 8% win on subsequent lookups in some scenarios. ''' </summary> ''' <remarks></remarks> Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)() ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' Does this symbol represent a missing assembly. ''' </summary> Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in the modules ''' of this assembly. If there is just one module in this assembly, this property just returns the ''' GlobalNamespace of that module. ''' </summary> Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. Detect cycles during lookup. ''' </summary> ''' <param name="emittedName"> ''' Full type name, possibly with generic name mangling. ''' </param> ''' <param name="visitedAssemblies"> ''' List of assemblies lookup has already visited (since type forwarding can introduce cycles). ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing ' This is a cache similar to the one used by MetaImport::GetTypeByName ' in native compiler. The difference is that native compiler pre-populates ' the cache when it loads types. Here we are populating the cache only ' with things we looked for, so that next time we are looking for the same ' thing, the lookup is fast. This cache also takes care of TypeForwarders. ' Gives about 8% win on subsequent lookups in some scenarios. ' ' CONSIDER !!! ' ' However, it is questionable how often subsequent lookup by name is going to happen. ' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name ' is done once and the result is cached. So, multiple lookups by name for the same type ' are going to happen only in these cases: ' 1) Resolving GetType() in attribute application, type is encoded by name. ' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type. ' 3) Different Module refers to the same type, lookup once per Module (with exception of #2). ' 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(emittedName) If result IsNot Nothing Then ' We only cache result equivalent to digging through type forwarders, which ' might produce a forwarder specific ErrorTypeSymbol. We don't want to ' return that error symbol, unless digThroughForwardedTypes Is true. If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then Return result End If ' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName) End If ' Now we will look for the type in each module of the assembly and pick the ' first type we find, this is what native VB compiler does. Dim modules = Me.Modules Dim count As Integer = modules.Length Dim i As Integer = 0 result = modules(i).LookupTopLevelMetadataType(emittedName) If TypeOf result Is MissingMetadataTypeSymbol Then For i = 1 To count - 1 Step 1 Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName) ' Hold on to the first missing type result, unless we found the type. If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then result = newResult Exit For End If Next End If Dim foundMatchInThisAssembly As Boolean = (i < count) Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me) If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then ' We didn't find the type Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol) Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False) If forwarded IsNot Nothing Then result = forwarded End If End If Debug.Assert(result IsNot Nothing) ' Add result of the lookup into the cache If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then CacheTopLevelMetadataType(emittedName, result) End If Return result End Function Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ''' <summary> ''' For test purposes only. ''' </summary> Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol Dim mdName = MetadataTypeName.FromFullName(emittedname) Return _emittedNameToTypeMap(mdName.ToKey()) End Function ''' <summary> ''' For test purposes only. ''' </summary> Friend ReadOnly Property EmittedNameToTypeMapCount As Integer Get Return _emittedNameToTypeMap.Count End Get End Property Private Function LookupTopLevelMetadataTypeInCache( ByRef emittedName As MetadataTypeName ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then Return result End If Return Nothing End Function Private Sub CacheTopLevelMetadataType( ByRef emittedName As MetadataTypeName, result As NamedTypeSymbol ) Dim result1 As NamedTypeSymbol = Nothing result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result) Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases 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 Imports System.Collections.Concurrent Imports System.Collections.ObjectModel Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents ''' an assembly that is not missing, i.e. the "real" thing. ''' </summary> Friend MustInherit Class NonMissingAssemblySymbol Inherits AssemblySymbol ''' <summary> ''' This is a cache similar to the one used by MetaImport::GetTypeByName ''' in native compiler. The difference is that native compiler pre-populates ''' the cache when it loads types. Here we are populating the cache only ''' with things we looked for, so that next time we are looking for the same ''' thing, the lookup is fast. This cache also takes care of TypeForwarders. ''' Gives about 8% win on subsequent lookups in some scenarios. ''' </summary> ''' <remarks></remarks> Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)() ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' Does this symbol represent a missing assembly. ''' </summary> Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in the modules ''' of this assembly. If there is just one module in this assembly, this property just returns the ''' GlobalNamespace of that module. ''' </summary> Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. Detect cycles during lookup. ''' </summary> ''' <param name="emittedName"> ''' Full type name, possibly with generic name mangling. ''' </param> ''' <param name="visitedAssemblies"> ''' List of assemblies lookup has already visited (since type forwarding can introduce cycles). ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing ' This is a cache similar to the one used by MetaImport::GetTypeByName ' in native compiler. The difference is that native compiler pre-populates ' the cache when it loads types. Here we are populating the cache only ' with things we looked for, so that next time we are looking for the same ' thing, the lookup is fast. This cache also takes care of TypeForwarders. ' Gives about 8% win on subsequent lookups in some scenarios. ' ' CONSIDER !!! ' ' However, it is questionable how often subsequent lookup by name is going to happen. ' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name ' is done once and the result is cached. So, multiple lookups by name for the same type ' are going to happen only in these cases: ' 1) Resolving GetType() in attribute application, type is encoded by name. ' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type. ' 3) Different Module refers to the same type, lookup once per Module (with exception of #2). ' 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(emittedName) If result IsNot Nothing Then ' We only cache result equivalent to digging through type forwarders, which ' might produce a forwarder specific ErrorTypeSymbol. We don't want to ' return that error symbol, unless digThroughForwardedTypes Is true. If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then Return result End If ' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName) End If ' Now we will look for the type in each module of the assembly and pick the ' first type we find, this is what native VB compiler does. Dim modules = Me.Modules Dim count As Integer = modules.Length Dim i As Integer = 0 result = modules(i).LookupTopLevelMetadataType(emittedName) If TypeOf result Is MissingMetadataTypeSymbol Then For i = 1 To count - 1 Step 1 Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName) ' Hold on to the first missing type result, unless we found the type. If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then result = newResult Exit For End If Next End If Dim foundMatchInThisAssembly As Boolean = (i < count) Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me) If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then ' We didn't find the type Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol) Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False) If forwarded IsNot Nothing Then result = forwarded End If End If Debug.Assert(result IsNot Nothing) ' Add result of the lookup into the cache If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then CacheTopLevelMetadataType(emittedName, result) End If Return result End Function Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ''' <summary> ''' For test purposes only. ''' </summary> Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol Dim mdName = MetadataTypeName.FromFullName(emittedname) Return _emittedNameToTypeMap(mdName.ToKey()) End Function ''' <summary> ''' For test purposes only. ''' </summary> Friend ReadOnly Property EmittedNameToTypeMapCount As Integer Get Return _emittedNameToTypeMap.Count End Get End Property Private Function LookupTopLevelMetadataTypeInCache( ByRef emittedName As MetadataTypeName ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then Return result End If Return Nothing End Function Private Sub CacheTopLevelMetadataType( ByRef emittedName As MetadataTypeName, result As NamedTypeSymbol ) Dim result1 As NamedTypeSymbol = Nothing result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result) Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/CodeAnalysisTest/CommonSyntaxTests.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.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal partial class SignatureHelpPresenter { private class SignatureHelpSource : ForegroundThreadAffinitizedObject, ISignatureHelpSource { public SignatureHelpSource(IThreadingContext threadingContext) : base(threadingContext) { } public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList<ISignature> signatures) { AssertIsForeground(); if (!session.Properties.TryGetProperty<SignatureHelpPresenterSession>(s_augmentSessionKey, out var presenterSession)) { return; } session.Properties.RemoveProperty(s_augmentSessionKey); presenterSession.AugmentSignatureHelpSession(signatures); } public ISignature GetBestMatch(ISignatureHelpSession session) { AssertIsForeground(); return session.SelectedSignature; } public void 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.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal partial class SignatureHelpPresenter { private class SignatureHelpSource : ForegroundThreadAffinitizedObject, ISignatureHelpSource { public SignatureHelpSource(IThreadingContext threadingContext) : base(threadingContext) { } public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList<ISignature> signatures) { AssertIsForeground(); if (!session.Properties.TryGetProperty<SignatureHelpPresenterSession>(s_augmentSessionKey, out var presenterSession)) { return; } session.Properties.RemoveProperty(s_augmentSessionKey); presenterSession.AugmentSignatureHelpSession(signatures); } public ISignature GetBestMatch(ISignatureHelpSession session) { AssertIsForeground(); return session.SelectedSignature; } public void Dispose() { } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { [Export(typeof(ICommandHandler))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Gets block comments by parsing the text for comment markers. /// </summary> protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var allText = snapshot.AsText(); var commentedSpans = ArrayBuilder<TextSpan>.GetInstance(); var openIdx = 0; while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0) { // Retrieve the first closing marker located after the open index. var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true); // If an open marker is found without a close marker, it's an unclosed comment. if (closeIdx < 0) { closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length; } var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx); commentedSpans.Add(blockCommentSpan); openIdx = closeIdx; } return Task.FromResult(commentedSpans.ToImmutableAndFree()); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { [Export(typeof(ICommandHandler))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Gets block comments by parsing the text for comment markers. /// </summary> protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var allText = snapshot.AsText(); var commentedSpans = ArrayBuilder<TextSpan>.GetInstance(); var openIdx = 0; while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0) { // Retrieve the first closing marker located after the open index. var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true); // If an open marker is found without a close marker, it's an unclosed comment. if (closeIdx < 0) { closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length; } var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx); commentedSpans.Add(blockCommentSpan); openIdx = closeIdx; } return Task.FromResult(commentedSpans.ToImmutableAndFree()); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Symbols/TypeSymbol.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 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. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 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. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { get; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/Core/Def/ValueTracking/BindableTextBlock.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class BindableTextBlock : TextBlock { public IList<Inline> InlineCollection { get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBlock = (BindableTextBlock)sender; var newList = (IList<Inline>)e.NewValue; textBlock.Inlines.Clear(); foreach (var inline in newList) { textBlock.Inlines.Add(inline); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class BindableTextBlock : TextBlock { public IList<Inline> InlineCollection { get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBlock = (BindableTextBlock)sender; var newList = (IList<Inline>)e.NewValue; textBlock.Inlines.Clear(); foreach (var inline in newList) { textBlock.Inlines.Add(inline); } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/Core/Portable/Shared/Utilities/DocumentationComment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Xml; using XmlNames = Roslyn.Utilities.DocumentationCommentXmlNames; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// A documentation comment derived from either source text or metadata. /// </summary> internal sealed class DocumentationComment { /// <summary> /// True if an error occurred when parsing. /// </summary> public bool HadXmlParseError { get; private set; } /// <summary> /// The full XML text of this tag. /// </summary> public string FullXmlFragment { get; private set; } /// <summary> /// The text in the &lt;example&gt; tag. Null if no tag existed. /// </summary> public string? ExampleText { get; private set; } /// <summary> /// The text in the &lt;summary&gt; tag. Null if no tag existed. /// </summary> public string? SummaryText { get; private set; } /// <summary> /// The text in the &lt;returns&gt; tag. Null if no tag existed. /// </summary> public string? ReturnsText { get; private set; } /// <summary> /// The text in the &lt;value&gt; tag. Null if no tag existed. /// </summary> public string? ValueText { get; private set; } /// <summary> /// The text in the &lt;remarks&gt; tag. Null if no tag existed. /// </summary> public string? RemarksText { get; private set; } /// <summary> /// The names of items in &lt;param&gt; tags. /// </summary> public ImmutableArray<string> ParameterNames { get; private set; } /// <summary> /// The names of items in &lt;typeparam&gt; tags. /// </summary> public ImmutableArray<string> TypeParameterNames { get; private set; } /// <summary> /// The types of items in &lt;exception&gt; tags. /// </summary> public ImmutableArray<string> ExceptionTypes { get; private set; } /// <summary> /// The item named in the &lt;completionlist&gt; tag's cref attribute. /// Null if the tag or cref attribute didn't exist. /// </summary> public string? CompletionListCref { get; private set; } /// <summary> /// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string /// </summary> private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" }; private DocumentationComment(string fullXmlFragment) { FullXmlFragment = fullXmlFragment; ParameterNames = ImmutableArray<string>.Empty; TypeParameterNames = ImmutableArray<string>.Empty; ExceptionTypes = ImmutableArray<string>.Empty; } /// <summary> /// Cache of the most recently parsed fragment and the resulting DocumentationComment /// </summary> private static volatile DocumentationComment? s_cacheLastXmlFragmentParse; /// <summary> /// Parses and constructs a <see cref="DocumentationComment" /> from the given fragment of XML. /// </summary> /// <param name="xml">The fragment of XML to parse.</param> /// <returns>A DocumentationComment instance.</returns> public static DocumentationComment FromXmlFragment(string xml) { var result = s_cacheLastXmlFragmentParse; if (result == null || result.FullXmlFragment != xml) { // Cache miss result = CommentBuilder.Parse(xml); s_cacheLastXmlFragmentParse = result; } return result; } /// <summary> /// Helper class for parsing XML doc comments. Encapsulates the state required during parsing. /// </summary> private class CommentBuilder { private readonly DocumentationComment _comment; private ImmutableArray<string>.Builder? _parameterNamesBuilder; private ImmutableArray<string>.Builder? _typeParameterNamesBuilder; private ImmutableArray<string>.Builder? _exceptionTypesBuilder; private Dictionary<string, ImmutableArray<string>.Builder>? _exceptionTextBuilders; /// <summary> /// Parse and construct a <see cref="DocumentationComment" /> from the given fragment of XML. /// </summary> /// <param name="xml">The fragment of XML to parse.</param> /// <returns>A DocumentationComment instance.</returns> public static DocumentationComment Parse(string xml) { try { return new CommentBuilder(xml).ParseInternal(xml); } catch (Exception) { // It would be nice if we only had to catch XmlException to handle invalid XML // while parsing doc comments. Unfortunately, other exceptions can also occur, // so we just catch them all. See Dev12 Bug 612456 for an example. return new DocumentationComment(xml) { HadXmlParseError = true }; } } private CommentBuilder(string xml) => _comment = new DocumentationComment(xml); private DocumentationComment ParseInternal(string xml) { XmlFragmentParser.ParseFragment(xml, ParseCallback, this); if (_exceptionTextBuilders != null) { foreach (var typeAndBuilderPair in _exceptionTextBuilders) { _comment._exceptionTexts.Add(typeAndBuilderPair.Key, typeAndBuilderPair.Value.AsImmutable()); } } _comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable(); _comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable(); _comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable(); return _comment; } private static void ParseCallback(XmlReader reader, CommentBuilder builder) => builder.ParseCallback(reader); private static string TrimEachLine(string text) => string.Join(Environment.NewLine, text.Split(s_NewLineAsStringArray, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim())); private void ParseCallback(XmlReader reader) { if (reader.NodeType == XmlNodeType.Element) { var localName = reader.LocalName; if (XmlNames.ElementEquals(localName, XmlNames.ExampleElementName) && _comment.ExampleText == null) { _comment.ExampleText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.SummaryElementName) && _comment.SummaryText == null) { _comment.SummaryText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ReturnsElementName) && _comment.ReturnsText == null) { _comment.ReturnsText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ValueElementName) && _comment.ValueText == null) { _comment.ValueText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.RemarksElementName) && _comment.RemarksText == null) { _comment.RemarksText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ParameterElementName)) { var name = reader.GetAttribute(XmlNames.NameAttributeName); var paramText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(name) && !_comment._parameterTexts.ContainsKey(name)) { (_parameterNamesBuilder ?? (_parameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name); _comment._parameterTexts.Add(name, TrimEachLine(paramText)); } } else if (XmlNames.ElementEquals(localName, XmlNames.TypeParameterElementName)) { var name = reader.GetAttribute(XmlNames.NameAttributeName); var typeParamText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(name) && !_comment._typeParameterTexts.ContainsKey(name)) { (_typeParameterNamesBuilder ?? (_typeParameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name); _comment._typeParameterTexts.Add(name, TrimEachLine(typeParamText)); } } else if (XmlNames.ElementEquals(localName, XmlNames.ExceptionElementName)) { var type = reader.GetAttribute(XmlNames.CrefAttributeName); var exceptionText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(type)) { if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type)) { (_exceptionTypesBuilder ?? (_exceptionTypesBuilder = ImmutableArray.CreateBuilder<string>())).Add(type); (_exceptionTextBuilders ?? (_exceptionTextBuilders = new Dictionary<string, ImmutableArray<string>.Builder>())).Add(type, ImmutableArray.CreateBuilder<string>()); } _exceptionTextBuilders[type].Add(exceptionText); } } else if (XmlNames.ElementEquals(localName, XmlNames.CompletionListElementName)) { var cref = reader.GetAttribute(XmlNames.CrefAttributeName); if (!string.IsNullOrWhiteSpace(cref)) { _comment.CompletionListCref = cref; } reader.ReadInnerXml(); } else { // This is an element we don't handle. Skip it. reader.Read(); } } else { // We came across something that isn't a start element, like a block of text. // Skip it. reader.Read(); } } } private readonly Dictionary<string, string> _parameterTexts = new(); private readonly Dictionary<string, string> _typeParameterTexts = new(); private readonly Dictionary<string, ImmutableArray<string>> _exceptionTexts = new(); /// <summary> /// Returns the text for a given parameter, or null if no documentation was given for the parameter. /// </summary> public string? GetParameterText(string parameterName) { _parameterTexts.TryGetValue(parameterName, out var text); return text; } /// <summary> /// Returns the text for a given type parameter, or null if no documentation was given for the type parameter. /// </summary> public string? GetTypeParameterText(string typeParameterName) { _typeParameterTexts.TryGetValue(typeParameterName, out var text); return text; } /// <summary> /// Returns the texts for a given exception, or an empty <see cref="ImmutableArray"/> if no documentation was given for the exception. /// </summary> public ImmutableArray<string> GetExceptionTexts(string exceptionName) { _exceptionTexts.TryGetValue(exceptionName, out var texts); if (texts.IsDefault) { // If the exception wasn't found, TryGetValue will set "texts" to a default value. // To be friendly, we want to return an empty array rather than a null array. texts = ImmutableArray.Create<string>(); } return texts; } /// <summary> /// An empty comment. /// </summary> public static readonly DocumentationComment Empty = new(string.Empty); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Xml; using XmlNames = Roslyn.Utilities.DocumentationCommentXmlNames; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// A documentation comment derived from either source text or metadata. /// </summary> internal sealed class DocumentationComment { /// <summary> /// True if an error occurred when parsing. /// </summary> public bool HadXmlParseError { get; private set; } /// <summary> /// The full XML text of this tag. /// </summary> public string FullXmlFragment { get; private set; } /// <summary> /// The text in the &lt;example&gt; tag. Null if no tag existed. /// </summary> public string? ExampleText { get; private set; } /// <summary> /// The text in the &lt;summary&gt; tag. Null if no tag existed. /// </summary> public string? SummaryText { get; private set; } /// <summary> /// The text in the &lt;returns&gt; tag. Null if no tag existed. /// </summary> public string? ReturnsText { get; private set; } /// <summary> /// The text in the &lt;value&gt; tag. Null if no tag existed. /// </summary> public string? ValueText { get; private set; } /// <summary> /// The text in the &lt;remarks&gt; tag. Null if no tag existed. /// </summary> public string? RemarksText { get; private set; } /// <summary> /// The names of items in &lt;param&gt; tags. /// </summary> public ImmutableArray<string> ParameterNames { get; private set; } /// <summary> /// The names of items in &lt;typeparam&gt; tags. /// </summary> public ImmutableArray<string> TypeParameterNames { get; private set; } /// <summary> /// The types of items in &lt;exception&gt; tags. /// </summary> public ImmutableArray<string> ExceptionTypes { get; private set; } /// <summary> /// The item named in the &lt;completionlist&gt; tag's cref attribute. /// Null if the tag or cref attribute didn't exist. /// </summary> public string? CompletionListCref { get; private set; } /// <summary> /// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string /// </summary> private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" }; private DocumentationComment(string fullXmlFragment) { FullXmlFragment = fullXmlFragment; ParameterNames = ImmutableArray<string>.Empty; TypeParameterNames = ImmutableArray<string>.Empty; ExceptionTypes = ImmutableArray<string>.Empty; } /// <summary> /// Cache of the most recently parsed fragment and the resulting DocumentationComment /// </summary> private static volatile DocumentationComment? s_cacheLastXmlFragmentParse; /// <summary> /// Parses and constructs a <see cref="DocumentationComment" /> from the given fragment of XML. /// </summary> /// <param name="xml">The fragment of XML to parse.</param> /// <returns>A DocumentationComment instance.</returns> public static DocumentationComment FromXmlFragment(string xml) { var result = s_cacheLastXmlFragmentParse; if (result == null || result.FullXmlFragment != xml) { // Cache miss result = CommentBuilder.Parse(xml); s_cacheLastXmlFragmentParse = result; } return result; } /// <summary> /// Helper class for parsing XML doc comments. Encapsulates the state required during parsing. /// </summary> private class CommentBuilder { private readonly DocumentationComment _comment; private ImmutableArray<string>.Builder? _parameterNamesBuilder; private ImmutableArray<string>.Builder? _typeParameterNamesBuilder; private ImmutableArray<string>.Builder? _exceptionTypesBuilder; private Dictionary<string, ImmutableArray<string>.Builder>? _exceptionTextBuilders; /// <summary> /// Parse and construct a <see cref="DocumentationComment" /> from the given fragment of XML. /// </summary> /// <param name="xml">The fragment of XML to parse.</param> /// <returns>A DocumentationComment instance.</returns> public static DocumentationComment Parse(string xml) { try { return new CommentBuilder(xml).ParseInternal(xml); } catch (Exception) { // It would be nice if we only had to catch XmlException to handle invalid XML // while parsing doc comments. Unfortunately, other exceptions can also occur, // so we just catch them all. See Dev12 Bug 612456 for an example. return new DocumentationComment(xml) { HadXmlParseError = true }; } } private CommentBuilder(string xml) => _comment = new DocumentationComment(xml); private DocumentationComment ParseInternal(string xml) { XmlFragmentParser.ParseFragment(xml, ParseCallback, this); if (_exceptionTextBuilders != null) { foreach (var typeAndBuilderPair in _exceptionTextBuilders) { _comment._exceptionTexts.Add(typeAndBuilderPair.Key, typeAndBuilderPair.Value.AsImmutable()); } } _comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable(); _comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable(); _comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable(); return _comment; } private static void ParseCallback(XmlReader reader, CommentBuilder builder) => builder.ParseCallback(reader); private static string TrimEachLine(string text) => string.Join(Environment.NewLine, text.Split(s_NewLineAsStringArray, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim())); private void ParseCallback(XmlReader reader) { if (reader.NodeType == XmlNodeType.Element) { var localName = reader.LocalName; if (XmlNames.ElementEquals(localName, XmlNames.ExampleElementName) && _comment.ExampleText == null) { _comment.ExampleText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.SummaryElementName) && _comment.SummaryText == null) { _comment.SummaryText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ReturnsElementName) && _comment.ReturnsText == null) { _comment.ReturnsText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ValueElementName) && _comment.ValueText == null) { _comment.ValueText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.RemarksElementName) && _comment.RemarksText == null) { _comment.RemarksText = TrimEachLine(reader.ReadInnerXml()); } else if (XmlNames.ElementEquals(localName, XmlNames.ParameterElementName)) { var name = reader.GetAttribute(XmlNames.NameAttributeName); var paramText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(name) && !_comment._parameterTexts.ContainsKey(name)) { (_parameterNamesBuilder ?? (_parameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name); _comment._parameterTexts.Add(name, TrimEachLine(paramText)); } } else if (XmlNames.ElementEquals(localName, XmlNames.TypeParameterElementName)) { var name = reader.GetAttribute(XmlNames.NameAttributeName); var typeParamText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(name) && !_comment._typeParameterTexts.ContainsKey(name)) { (_typeParameterNamesBuilder ?? (_typeParameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name); _comment._typeParameterTexts.Add(name, TrimEachLine(typeParamText)); } } else if (XmlNames.ElementEquals(localName, XmlNames.ExceptionElementName)) { var type = reader.GetAttribute(XmlNames.CrefAttributeName); var exceptionText = reader.ReadInnerXml(); if (!string.IsNullOrWhiteSpace(type)) { if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type)) { (_exceptionTypesBuilder ?? (_exceptionTypesBuilder = ImmutableArray.CreateBuilder<string>())).Add(type); (_exceptionTextBuilders ?? (_exceptionTextBuilders = new Dictionary<string, ImmutableArray<string>.Builder>())).Add(type, ImmutableArray.CreateBuilder<string>()); } _exceptionTextBuilders[type].Add(exceptionText); } } else if (XmlNames.ElementEquals(localName, XmlNames.CompletionListElementName)) { var cref = reader.GetAttribute(XmlNames.CrefAttributeName); if (!string.IsNullOrWhiteSpace(cref)) { _comment.CompletionListCref = cref; } reader.ReadInnerXml(); } else { // This is an element we don't handle. Skip it. reader.Read(); } } else { // We came across something that isn't a start element, like a block of text. // Skip it. reader.Read(); } } } private readonly Dictionary<string, string> _parameterTexts = new(); private readonly Dictionary<string, string> _typeParameterTexts = new(); private readonly Dictionary<string, ImmutableArray<string>> _exceptionTexts = new(); /// <summary> /// Returns the text for a given parameter, or null if no documentation was given for the parameter. /// </summary> public string? GetParameterText(string parameterName) { _parameterTexts.TryGetValue(parameterName, out var text); return text; } /// <summary> /// Returns the text for a given type parameter, or null if no documentation was given for the type parameter. /// </summary> public string? GetTypeParameterText(string typeParameterName) { _typeParameterTexts.TryGetValue(typeParameterName, out var text); return text; } /// <summary> /// Returns the texts for a given exception, or an empty <see cref="ImmutableArray"/> if no documentation was given for the exception. /// </summary> public ImmutableArray<string> GetExceptionTexts(string exceptionName) { _exceptionTexts.TryGetValue(exceptionName, out var texts); if (texts.IsDefault) { // If the exception wasn't found, TryGetValue will set "texts" to a default value. // To be friendly, we want to return an empty array rather than a null array. texts = ImmutableArray.Create<string>(); } return texts; } /// <summary> /// An empty comment. /// </summary> public static readonly DocumentationComment Empty = new(string.Empty); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Operations/IOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// Root type for representing the abstract semantics of C# and VB statements and expressions. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> [InternalImplementationOnly] public interface IOperation { /// <summary> /// IOperation that has this operation as a child. Null for the root. /// </summary> IOperation? Parent { get; } /// <summary> /// Identifies the kind of the operation. /// </summary> OperationKind Kind { get; } /// <summary> /// Syntax that was analyzed to produce the operation. /// </summary> SyntaxNode Syntax { get; } /// <summary> /// Result type of the operation, or null if the operation does not produce a result. /// </summary> ITypeSymbol? Type { get; } /// <summary> /// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false. /// </summary> Optional<object?> ConstantValue { get; } /// <summary> /// An array of child operations for this operation. /// </summary> IEnumerable<IOperation> Children { get; } /// <summary> /// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>. /// </summary> string Language { get; } void Accept(OperationVisitor visitor); TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument); /// <summary> /// Set to True if compiler generated /implicitly computed by compiler code /// </summary> bool IsImplicit { get; } /// <summary> /// Optional semantic model that was used to generate this operation. /// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API /// and operation callbacks made to analyzers. /// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>. /// </summary> SemanticModel? SemanticModel { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// Root type for representing the abstract semantics of C# and VB statements and expressions. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> [InternalImplementationOnly] public interface IOperation { /// <summary> /// IOperation that has this operation as a child. Null for the root. /// </summary> IOperation? Parent { get; } /// <summary> /// Identifies the kind of the operation. /// </summary> OperationKind Kind { get; } /// <summary> /// Syntax that was analyzed to produce the operation. /// </summary> SyntaxNode Syntax { get; } /// <summary> /// Result type of the operation, or null if the operation does not produce a result. /// </summary> ITypeSymbol? Type { get; } /// <summary> /// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false. /// </summary> Optional<object?> ConstantValue { get; } /// <summary> /// An array of child operations for this operation. /// </summary> IEnumerable<IOperation> Children { get; } /// <summary> /// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>. /// </summary> string Language { get; } void Accept(OperationVisitor visitor); TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument); /// <summary> /// Set to True if compiler generated /implicitly computed by compiler code /// </summary> bool IsImplicit { get; } /// <summary> /// Optional semantic model that was used to generate this operation. /// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API /// and operation callbacks made to analyzers. /// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>. /// </summary> SemanticModel? SemanticModel { get; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/UnusedReferences/ReferenceUpdate.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.UnusedReferences { internal sealed class ReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public UpdateAction Action { get; set; } /// <summary> /// Gets the reference to be updated. /// </summary> public ReferenceInfo ReferenceInfo { get; } public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
// Licensed to the .NET Foundation under one or more 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.UnusedReferences { internal sealed class ReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public UpdateAction Action { get; set; } /// <summary> /// Gets the reference to be updated. /// </summary> public ReferenceInfo ReferenceInfo { get; } public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.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 EventDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, eventDeclaration As EventStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(eventDeclaration, spans, optionProvider) Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax) If Not block?.EndEventStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=eventDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) CollectCommentsRegions(block.EndEventStatement, spans, optionProvider) End If 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 EventDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, eventDeclaration As EventStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(eventDeclaration, spans, optionProvider) Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax) If Not block?.EndEventStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=eventDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) CollectCommentsRegions(block.EndEventStatement, spans, optionProvider) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormattingService.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.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Diagnostics #If Not CODE_STYLE Then Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting #If Not CODE_STYLE Then <ExportLanguageService(GetType(ISyntaxFormattingService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxFormattingService #Else Friend Class VisualBasicSyntaxFormattingService #End If Inherits AbstractSyntaxFormattingService Private ReadOnly _rules As ImmutableList(Of AbstractFormattingRule) #If CODE_STYLE Then Public Shared ReadOnly Instance As New VisualBasicSyntaxFormattingService #End If #If Not CODE_STYLE Then <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() #Else Public Sub New() #End If _rules = ImmutableList.Create(Of AbstractFormattingRule)( New StructuredTriviaFormattingRule(), New ElasticTriviaFormattingRule(), New AdjustSpaceFormattingRule(), New AlignTokensFormattingRule(), New NodeBasedFormattingRule(), DefaultOperationProvider.Instance) End Sub Public Overrides Function GetDefaultFormattingRules() As IEnumerable(Of AbstractFormattingRule) Return _rules End Function Protected Overrides Function CreateAggregatedFormattingResult(node As SyntaxNode, results As IList(Of AbstractFormattingResult), Optional formattingSpans As SimpleIntervalTree(Of TextSpan, TextSpanIntervalIntrospector) = Nothing) As IFormattingResult Return New AggregatedFormattingResult(node, results, formattingSpans) End Function Protected Overrides Function Format(root As SyntaxNode, options As AnalyzerConfigOptions, formattingRules As IEnumerable(Of AbstractFormattingRule), token1 As SyntaxToken, token2 As SyntaxToken, cancellationToken As CancellationToken) As AbstractFormattingResult Return New VisualBasicFormatEngine(root, options, formattingRules, token1, token2).Format(cancellationToken) 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.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Diagnostics #If Not CODE_STYLE Then Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting #If Not CODE_STYLE Then <ExportLanguageService(GetType(ISyntaxFormattingService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxFormattingService #Else Friend Class VisualBasicSyntaxFormattingService #End If Inherits AbstractSyntaxFormattingService Private ReadOnly _rules As ImmutableList(Of AbstractFormattingRule) #If CODE_STYLE Then Public Shared ReadOnly Instance As New VisualBasicSyntaxFormattingService #End If #If Not CODE_STYLE Then <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() #Else Public Sub New() #End If _rules = ImmutableList.Create(Of AbstractFormattingRule)( New StructuredTriviaFormattingRule(), New ElasticTriviaFormattingRule(), New AdjustSpaceFormattingRule(), New AlignTokensFormattingRule(), New NodeBasedFormattingRule(), DefaultOperationProvider.Instance) End Sub Public Overrides Function GetDefaultFormattingRules() As IEnumerable(Of AbstractFormattingRule) Return _rules End Function Protected Overrides Function CreateAggregatedFormattingResult(node As SyntaxNode, results As IList(Of AbstractFormattingResult), Optional formattingSpans As SimpleIntervalTree(Of TextSpan, TextSpanIntervalIntrospector) = Nothing) As IFormattingResult Return New AggregatedFormattingResult(node, results, formattingSpans) End Function Protected Overrides Function Format(root As SyntaxNode, options As AnalyzerConfigOptions, formattingRules As IEnumerable(Of AbstractFormattingRule), token1 As SyntaxToken, token2 As SyntaxToken, cancellationToken As CancellationToken) As AbstractFormattingResult Return New VisualBasicFormatEngine(root, options, formattingRules, token1, token2).Format(cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/VisualBasic/Portable/Formatting/VisualBasicNewDocumentFormattingService.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.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting <ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicNewDocumentFormattingService Inherits AbstractNewDocumentFormattingService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata))) MyBase.New(providers) End Sub Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic 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.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting <ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicNewDocumentFormattingService Inherits AbstractNewDocumentFormattingService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata))) MyBase.New(providers) End Sub Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/EnumerableExtensions.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; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public static class EnumerableExtensions { public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector) { int i = 0; foreach (var item in items) { yield return selector(item, i++); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public static class EnumerableExtensions { public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector) { int i = 0; foreach (var item in items) { yield return selector(item, i++); } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/GenerateConstructor/GenerateConstructorCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.GenerateMember; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { internal static class GenerateConstructorDiagnosticIds { public const string CS0122 = nameof(CS0122); // CS0122: 'C' is inaccessible due to its protection level public const string CS1729 = nameof(CS1729); // CS1729: 'C' does not contain a constructor that takes n arguments public const string CS1739 = nameof(CS1739); // CS1739: The best overload for 'Program' does not have a parameter named 'v' public const string CS1503 = nameof(CS1503); // CS1503: Argument 1: cannot convert from 'T1' to 'T2' public const string CS1660 = nameof(CS1660); // CS1660: Cannot convert lambda expression to type 'string[]' because it is not a delegate type public const string CS7036 = nameof(CS7036); // CS7036: There is no argument given that corresponds to the required formal parameter 'v' of 'C.C(int)' public static readonly ImmutableArray<string> AllDiagnosticIds = ImmutableArray.Create(CS0122, CS1729, CS1739, CS1503, CS1660, CS7036); public static readonly ImmutableArray<string> TooManyArgumentsDiagnosticIds = ImmutableArray.Create(CS1729); public static readonly ImmutableArray<string> CannotConvertDiagnosticIds = ImmutableArray.Create(CS1503, CS1660); } /// <summary> /// This <see cref="CodeFixProvider"/> gives users a way to generate constructors for an existing /// type when a user tries to 'new' up an instance of that type with a set of parameter that does /// not match any existing constructor. i.e. it is the equivalent of 'Generate-Method' but for /// constructors. Parameters for the constructor will be picked in a manner similar to Generate- /// Method. However, this type will also attempt to hook up those parameters to existing fields /// and properties, or pass them to a this/base constructor if available. /// /// Importantly, this type is not responsible for generating constructors for a type based on /// the user selecting some fields/properties of that type. Nor is it responsible for generating /// derived class constructors for all unmatched base class constructors in a type hierarchy. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConstructor), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)] internal class GenerateConstructorCodeFixProvider : AbstractGenerateMemberCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateConstructorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => GenerateConstructorDiagnosticIds.AllDiagnosticIds; protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { var service = document.GetLanguageService<IGenerateConstructorService>(); return service.GenerateConstructorAsync(document, node, cancellationToken); } protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic) { return node is BaseObjectCreationExpressionSyntax || node is ConstructorInitializerSyntax || node is AttributeSyntax; } protected override SyntaxNode GetTargetNode(SyntaxNode node) { switch (node) { case ObjectCreationExpressionSyntax objectCreationNode: return objectCreationNode.Type.GetRightmostName(); case AttributeSyntax attributeNode: return attributeNode.Name; } return node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.GenerateMember; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { internal static class GenerateConstructorDiagnosticIds { public const string CS0122 = nameof(CS0122); // CS0122: 'C' is inaccessible due to its protection level public const string CS1729 = nameof(CS1729); // CS1729: 'C' does not contain a constructor that takes n arguments public const string CS1739 = nameof(CS1739); // CS1739: The best overload for 'Program' does not have a parameter named 'v' public const string CS1503 = nameof(CS1503); // CS1503: Argument 1: cannot convert from 'T1' to 'T2' public const string CS1660 = nameof(CS1660); // CS1660: Cannot convert lambda expression to type 'string[]' because it is not a delegate type public const string CS7036 = nameof(CS7036); // CS7036: There is no argument given that corresponds to the required formal parameter 'v' of 'C.C(int)' public static readonly ImmutableArray<string> AllDiagnosticIds = ImmutableArray.Create(CS0122, CS1729, CS1739, CS1503, CS1660, CS7036); public static readonly ImmutableArray<string> TooManyArgumentsDiagnosticIds = ImmutableArray.Create(CS1729); public static readonly ImmutableArray<string> CannotConvertDiagnosticIds = ImmutableArray.Create(CS1503, CS1660); } /// <summary> /// This <see cref="CodeFixProvider"/> gives users a way to generate constructors for an existing /// type when a user tries to 'new' up an instance of that type with a set of parameter that does /// not match any existing constructor. i.e. it is the equivalent of 'Generate-Method' but for /// constructors. Parameters for the constructor will be picked in a manner similar to Generate- /// Method. However, this type will also attempt to hook up those parameters to existing fields /// and properties, or pass them to a this/base constructor if available. /// /// Importantly, this type is not responsible for generating constructors for a type based on /// the user selecting some fields/properties of that type. Nor is it responsible for generating /// derived class constructors for all unmatched base class constructors in a type hierarchy. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConstructor), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)] internal class GenerateConstructorCodeFixProvider : AbstractGenerateMemberCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateConstructorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => GenerateConstructorDiagnosticIds.AllDiagnosticIds; protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { var service = document.GetLanguageService<IGenerateConstructorService>(); return service.GenerateConstructorAsync(document, node, cancellationToken); } protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic) { return node is BaseObjectCreationExpressionSyntax || node is ConstructorInitializerSyntax || node is AttributeSyntax; } protected override SyntaxNode GetTargetNode(SyntaxNode node) { switch (node) { case ObjectCreationExpressionSyntax objectCreationNode: return objectCreationNode.Type.GetRightmostName(); case AttributeSyntax attributeNode: return attributeNode.Name; } return node; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefConstruction.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.Host.Mef { internal static class MefConstruction { internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; internal const string FactoryMethodMessage = "This factory method only provides services for the MEF export provider."; } }
// Licensed to the .NET Foundation under one or more 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.Host.Mef { internal static class MefConstruction { internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider."; internal const string FactoryMethodMessage = "This factory method only provides services for the MEF export provider."; } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle { public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider()); } public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = false:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = false:suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion dotnet_style_object_initializerr = false </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion dotnet_style_object_initializerr = false # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error dotnet_style_object_initializer = true:warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error dotnet_style_object_initializer = false:warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = true:suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle { public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider()); } public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = false:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = false:suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_True() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion dotnet_style_object_initializerr = false </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion dotnet_style_object_initializerr = false # IDE0017: Simplify object initialization dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error dotnet_style_object_initializer = true:warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error dotnet_style_object_initializer = false:warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_style_object_initializer = true:suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_False() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = false:suggestion # IDE0017: Simplify object initialization dotnet_style_object_initializer = false </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_GetHashCodeMethodSymbol.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.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousTypeGetHashCodeMethodSymbol Inherits SynthesizedRegularMethodBase Public Sub New(container As AnonymousTypeTemplateSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectGetHashCode) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Me.AnonymousType.Manager.System_Object__GetHashCode End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Int32 End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable 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 Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousTypeGetHashCodeMethodSymbol Inherits SynthesizedRegularMethodBase Public Sub New(container As AnonymousTypeTemplateSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectGetHashCode) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Me.AnonymousType.Manager.System_Object__GetHashCode End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Int32 End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ObjectWriterExtensions.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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ObjectWriterExtensions { public static void WriteArray<T>(this ObjectWriter writer, ImmutableArray<T> values, Action<ObjectWriter, T> write) { writer.WriteInt32(values.Length); foreach (var val in values) write(writer, val); } } internal static class ObjectReaderExtensions { public static ImmutableArray<T> ReadArray<T>(this ObjectReader reader, Func<ObjectReader, T> read) { var length = reader.ReadInt32(); using var _ = ArrayBuilder<T>.GetInstance(length, out var builder); for (var i = 0; i < length; i++) builder.Add(read(reader)); 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. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ObjectWriterExtensions { public static void WriteArray<T>(this ObjectWriter writer, ImmutableArray<T> values, Action<ObjectWriter, T> write) { writer.WriteInt32(values.Length); foreach (var val in values) write(writer, val); } } internal static class ObjectReaderExtensions { public static ImmutableArray<T> ReadArray<T>(this ObjectReader reader, Func<ObjectReader, T> read) { var length = reader.ReadInt32(); using var _ = ArrayBuilder<T>.GetInstance(length, out var builder); for (var i = 0; i < length; i++) builder.Add(read(reader)); return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.OLE.Interop Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.Shell Imports Roslyn.Utilities Imports System.IO Imports Moq Imports Microsoft.VisualStudio.LanguageServices.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Public NotInheritable Class MockHierarchy Implements IVsHierarchy Implements IVsProject3 Implements IVsAggregatableProject Implements IVsBuildPropertyStorage Public Shared ReadOnly ReferencesNodeItemId As UInteger = 123456 Private _projectName As String Private _projectBinPath As String Private _maxSupportedLangVer As String Private _runAnalyzers As String Private _runAnalyzersDuringLiveAnalysis As String Private ReadOnly _projectRefPath As String Private ReadOnly _projectCapabilities As String Private ReadOnly _projectMock As Mock(Of EnvDTE.Project) = New Mock(Of EnvDTE.Project)(MockBehavior.Strict) Private ReadOnly _eventSinks As New Dictionary(Of UInteger, IVsHierarchyEvents) Private ReadOnly _hierarchyItems As New Dictionary(Of UInteger, String) Public Sub New(projectName As String, projectFilePath As String, projectBinPath As String, projectRefPath As String, projectCapabilities As String) _projectName = projectName _projectBinPath = projectBinPath _projectRefPath = projectRefPath _projectCapabilities = projectCapabilities _hierarchyItems.Add(CType(VSConstants.VSITEMID.Root, UInteger), projectFilePath) End Sub Public Sub RenameProject(projectName As String) If _projectName = projectName Then Return End If _projectName = projectName For Each sink In _eventSinks.Values sink.OnPropertyChanged(VSConstants.VSITEMID.Root, __VSHPROPID.VSHPROPID_Name, 0) Next End Sub Public Function AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItem _hierarchyItems.Add(itemidLoc, pszItemName) Return VSConstants.S_OK End Function Public Function AddItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItemWithSpecific _hierarchyItems.Add(itemidLoc, pszItemName) Return VSConstants.S_OK End Function Public Function AdviseHierarchyEvents(pEventSink As IVsHierarchyEvents, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> ByRef pdwCookie As UInteger) As Integer Implements IVsHierarchy.AdviseHierarchyEvents pdwCookie = _eventSinks.Keys.Concat({0}).Max() + 1UI _eventSinks.Add(pdwCookie, pEventSink) Return VSConstants.S_OK End Function Public Function Close() As Integer Implements IVsHierarchy.Close _hierarchyItems.Clear() Return VSConstants.S_OK End Function Public Function GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject3.GenerateUniqueItemName Throw New NotImplementedException() End Function Public Function GetCanonicalName(itemid As UInteger, ByRef pbstrName As String) As Integer Implements IVsHierarchy.GetCanonicalName If _hierarchyItems.TryGetValue(itemid, pbstrName) Then Return VSConstants.S_OK Else Return VSConstants.E_FAIL End If End Function Public Function GetGuidProperty(itemid As UInteger, propid As Integer, ByRef pguid As Guid) As Integer Implements IVsHierarchy.GetGuidProperty If itemid = VSConstants.VSITEMID_ROOT And propid = CType(__VSHPROPID.VSHPROPID_ProjectIDGuid, Integer) Then pguid = Guid.NewGuid() Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject3.GetItemContext Throw New NotImplementedException() End Function Public Function GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject3.GetMkDocument _hierarchyItems.TryGetValue(itemid, pbstrMkDocument) Return VSConstants.S_OK End Function Public Function GetNestedHierarchy(itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidHierarchyNested As Guid, ByRef ppHierarchyNested As IntPtr, ByRef pitemidNested As UInteger) As Integer Implements IVsHierarchy.GetNestedHierarchy Throw New NotImplementedException() End Function Public Function GetProperty(itemid As UInteger, propid As Integer, ByRef pvar As Object) As Integer Implements IVsHierarchy.GetProperty If propid = __VSHPROPID.VSHPROPID_ProjectName Then pvar = _projectName Return VSConstants.S_OK ElseIf propid = __VSHPROPID5.VSHPROPID_ProjectCapabilities Then pvar = _projectCapabilities Return VSConstants.S_OK ElseIf propid = __VSHPROPID7.VSHPROPID_ProjectTreeCapabilities Then If itemid = ReferencesNodeItemId Then pvar = "References" Return VSConstants.S_OK End If ElseIf propid = __VSHPROPID.VSHPROPID_ExtObject Then Dim projectItemMock As Mock(Of EnvDTE.ProjectItem) = New Mock(Of EnvDTE.ProjectItem)(MockBehavior.Strict) projectItemMock.SetupGet(Function(m) m.ContainingProject).Returns(_projectMock.Object) projectItemMock.Setup(Function(m) m.FileNames(1)).Returns(_hierarchyItems(itemid)) pvar = projectItemMock.Object Return VSConstants.S_OK End If Return VSConstants.E_NOTIMPL End Function Public Function GetSite(ByRef ppSP As IServiceProvider) As Integer Implements IVsHierarchy.GetSite Throw New NotImplementedException() End Function Public Function IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject3.IsDocumentInProject pfFound = 0 For Each kvp In _hierarchyItems If kvp.Value = pszMkDocument Then pfFound = 1 pitemid = kvp.Key Exit For End If Next Return VSConstants.S_OK End Function Public Function OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItem Throw New NotImplementedException() End Function Public Function OpenItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItemWithSpecific Throw New NotImplementedException() End Function Public Function ParseCanonicalName(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, ByRef pitemid As UInteger) As Integer Implements IVsHierarchy.ParseCanonicalName For Each kvp In _hierarchyItems If kvp.Value = pszName Then pitemid = kvp.Key Exit For End If Next Return VSConstants.S_OK End Function Public Function QueryClose(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanClose As Integer) As Integer Implements IVsHierarchy.QueryClose Throw New NotImplementedException() End Function Public Function RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject3.RemoveItem _hierarchyItems.Remove(itemid) Return VSConstants.S_OK End Function Public Function ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.ReopenItem Throw New NotImplementedException() End Function Public Function SetGuidProperty(itemid As UInteger, propid As Integer, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguid As Guid) As Integer Implements IVsHierarchy.SetGuidProperty Throw New NotImplementedException() End Function Public Function SetProperty(itemid As UInteger, propid As Integer, var As Object) As Integer Implements IVsHierarchy.SetProperty If propid = __VSHPROPID.VSHPROPID_ProjectName Then _projectName = If(TryCast(var, String), _projectName) Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function SetSite(psp As IServiceProvider) As Integer Implements IVsHierarchy.SetSite Throw New NotImplementedException() End Function Public Function TransferItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentOld As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentNew As String, punkWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.TransferItem For Each kvp In _hierarchyItems If kvp.Value = pszMkDocumentOld Then _hierarchyItems(kvp.Key) = pszMkDocumentNew Exit For End If Next Return VSConstants.S_OK End Function Public Function UnadviseHierarchyEvents(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> dwCookie As UInteger) As Integer Implements IVsHierarchy.UnadviseHierarchyEvents If Not _eventSinks.Remove(dwCookie) Then Throw New InvalidOperationException("The cookie was not subscribed.") End If Return VSConstants.S_OK End Function Public Function Unused0() As Integer Implements IVsHierarchy.Unused0 Throw New NotImplementedException() End Function Public Function Unused1() As Integer Implements IVsHierarchy.Unused1 Throw New NotImplementedException() End Function Public Function Unused2() As Integer Implements IVsHierarchy.Unused2 Throw New NotImplementedException() End Function Public Function Unused3() As Integer Implements IVsHierarchy.Unused3 Throw New NotImplementedException() End Function Public Function Unused4() As Integer Implements IVsHierarchy.Unused4 Throw New NotImplementedException() End Function Private Function IVsProject2_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject2.AddItem Throw New NotImplementedException() End Function Private Function IVsProject2_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject2.GenerateUniqueItemName Throw New NotImplementedException() End Function Private Function IVsProject2_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject2.GetItemContext Throw New NotImplementedException() End Function Private Function IVsProject2_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject2.GetMkDocument Throw New NotImplementedException() End Function Private Function IVsProject2_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject2.IsDocumentInProject Throw New NotImplementedException() End Function Private Function IVsProject2_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.OpenItem Throw New NotImplementedException() End Function Private Function IVsProject2_RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject2.RemoveItem Throw New NotImplementedException() End Function Private Function IVsProject2_ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.ReopenItem Throw New NotImplementedException() End Function Private Function IVsProject_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject.AddItem Throw New NotImplementedException() End Function Private Function IVsProject_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject.GenerateUniqueItemName Throw New NotImplementedException() End Function Private Function IVsProject_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject.GetItemContext Throw New NotImplementedException() End Function Private Function IVsProject_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject.GetMkDocument Throw New NotImplementedException() End Function Private Function IVsProject_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject.IsDocumentInProject Throw New NotImplementedException() End Function Private Function IVsProject_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject.OpenItem Throw New NotImplementedException() End Function Public Function SetInnerProject(punkInner As Object) As Integer Implements IVsAggregatableProject.SetInnerProject Throw New NotImplementedException() End Function Public Function InitializeForOuter(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszFilename As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszLocation As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCREATEPROJFLAGS")> grfCreateFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidProject As Guid, ByRef ppvProject As IntPtr, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanceled As Integer) As Integer Implements IVsAggregatableProject.InitializeForOuter Throw New NotImplementedException() End Function Public Function OnAggregationComplete() As Integer Implements IVsAggregatableProject.OnAggregationComplete Throw New NotImplementedException() End Function Public Function GetAggregateProjectTypeGuids(ByRef pbstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.GetAggregateProjectTypeGuids If _projectCapabilities = "VB" Then pbstrProjTypeGuids = Guids.VisualBasicProjectIdString Return VSConstants.S_OK ElseIf _projectCapabilities = "CSharp" Then pbstrProjTypeGuids = Guids.CSharpProjectIdString Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function SetAggregateProjectTypeGuids(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> lpstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.SetAggregateProjectTypeGuids Throw New NotImplementedException() End Function Public Function GetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, ByRef pbstrPropValue As String) As Integer Implements IVsBuildPropertyStorage.GetPropertyValue If pszPropName = "OutDir" Then pbstrPropValue = _projectBinPath Return VSConstants.S_OK ElseIf pszPropName = "TargetFileName" Then pbstrPropValue = PathUtilities.ChangeExtension(_projectName, "dll") Return VSConstants.S_OK ElseIf pszPropName = "TargetRefPath" Then pbstrPropValue = _projectRefPath Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then pbstrPropValue = _maxSupportedLangVer Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then pbstrPropValue = _runAnalyzers Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then pbstrPropValue = _runAnalyzersDuringLiveAnalysis Return VSConstants.S_OK End If Throw New NotSupportedException($"{NameOf(MockHierarchy)}.{NameOf(GetPropertyValue)} does not support reading {pszPropName}.") End Function Public Function SetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, pszPropValue As String) As Integer Implements IVsBuildPropertyStorage.SetPropertyValue If pszPropName = "OutDir" Then _projectBinPath = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = "TargetFileName" Then _projectName = PathUtilities.GetFileName(pszPropValue, includeExtension:=False) Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then _maxSupportedLangVer = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then _runAnalyzers = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then _runAnalyzersDuringLiveAnalysis = pszPropValue Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function RemoveProperty(pszPropName As String, pszConfigName As String, storage As UInteger) As Integer Implements IVsBuildPropertyStorage.RemoveProperty Throw New NotImplementedException() End Function Public Function GetItemAttribute(item As UInteger, pszAttributeName As String, ByRef pbstrAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.GetItemAttribute Throw New NotImplementedException() End Function Public Function SetItemAttribute(item As UInteger, pszAttributeName As String, pszAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.SetItemAttribute Throw New NotImplementedException() 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.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.OLE.Interop Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.Shell Imports Roslyn.Utilities Imports System.IO Imports Moq Imports Microsoft.VisualStudio.LanguageServices.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Public NotInheritable Class MockHierarchy Implements IVsHierarchy Implements IVsProject3 Implements IVsAggregatableProject Implements IVsBuildPropertyStorage Public Shared ReadOnly ReferencesNodeItemId As UInteger = 123456 Private _projectName As String Private _projectBinPath As String Private _maxSupportedLangVer As String Private _runAnalyzers As String Private _runAnalyzersDuringLiveAnalysis As String Private ReadOnly _projectRefPath As String Private ReadOnly _projectCapabilities As String Private ReadOnly _projectMock As Mock(Of EnvDTE.Project) = New Mock(Of EnvDTE.Project)(MockBehavior.Strict) Private ReadOnly _eventSinks As New Dictionary(Of UInteger, IVsHierarchyEvents) Private ReadOnly _hierarchyItems As New Dictionary(Of UInteger, String) Public Sub New(projectName As String, projectFilePath As String, projectBinPath As String, projectRefPath As String, projectCapabilities As String) _projectName = projectName _projectBinPath = projectBinPath _projectRefPath = projectRefPath _projectCapabilities = projectCapabilities _hierarchyItems.Add(CType(VSConstants.VSITEMID.Root, UInteger), projectFilePath) End Sub Public Sub RenameProject(projectName As String) If _projectName = projectName Then Return End If _projectName = projectName For Each sink In _eventSinks.Values sink.OnPropertyChanged(VSConstants.VSITEMID.Root, __VSHPROPID.VSHPROPID_Name, 0) Next End Sub Public Function AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItem _hierarchyItems.Add(itemidLoc, pszItemName) Return VSConstants.S_OK End Function Public Function AddItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItemWithSpecific _hierarchyItems.Add(itemidLoc, pszItemName) Return VSConstants.S_OK End Function Public Function AdviseHierarchyEvents(pEventSink As IVsHierarchyEvents, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> ByRef pdwCookie As UInteger) As Integer Implements IVsHierarchy.AdviseHierarchyEvents pdwCookie = _eventSinks.Keys.Concat({0}).Max() + 1UI _eventSinks.Add(pdwCookie, pEventSink) Return VSConstants.S_OK End Function Public Function Close() As Integer Implements IVsHierarchy.Close _hierarchyItems.Clear() Return VSConstants.S_OK End Function Public Function GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject3.GenerateUniqueItemName Throw New NotImplementedException() End Function Public Function GetCanonicalName(itemid As UInteger, ByRef pbstrName As String) As Integer Implements IVsHierarchy.GetCanonicalName If _hierarchyItems.TryGetValue(itemid, pbstrName) Then Return VSConstants.S_OK Else Return VSConstants.E_FAIL End If End Function Public Function GetGuidProperty(itemid As UInteger, propid As Integer, ByRef pguid As Guid) As Integer Implements IVsHierarchy.GetGuidProperty If itemid = VSConstants.VSITEMID_ROOT And propid = CType(__VSHPROPID.VSHPROPID_ProjectIDGuid, Integer) Then pguid = Guid.NewGuid() Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject3.GetItemContext Throw New NotImplementedException() End Function Public Function GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject3.GetMkDocument _hierarchyItems.TryGetValue(itemid, pbstrMkDocument) Return VSConstants.S_OK End Function Public Function GetNestedHierarchy(itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidHierarchyNested As Guid, ByRef ppHierarchyNested As IntPtr, ByRef pitemidNested As UInteger) As Integer Implements IVsHierarchy.GetNestedHierarchy Throw New NotImplementedException() End Function Public Function GetProperty(itemid As UInteger, propid As Integer, ByRef pvar As Object) As Integer Implements IVsHierarchy.GetProperty If propid = __VSHPROPID.VSHPROPID_ProjectName Then pvar = _projectName Return VSConstants.S_OK ElseIf propid = __VSHPROPID5.VSHPROPID_ProjectCapabilities Then pvar = _projectCapabilities Return VSConstants.S_OK ElseIf propid = __VSHPROPID7.VSHPROPID_ProjectTreeCapabilities Then If itemid = ReferencesNodeItemId Then pvar = "References" Return VSConstants.S_OK End If ElseIf propid = __VSHPROPID.VSHPROPID_ExtObject Then Dim projectItemMock As Mock(Of EnvDTE.ProjectItem) = New Mock(Of EnvDTE.ProjectItem)(MockBehavior.Strict) projectItemMock.SetupGet(Function(m) m.ContainingProject).Returns(_projectMock.Object) projectItemMock.Setup(Function(m) m.FileNames(1)).Returns(_hierarchyItems(itemid)) pvar = projectItemMock.Object Return VSConstants.S_OK End If Return VSConstants.E_NOTIMPL End Function Public Function GetSite(ByRef ppSP As IServiceProvider) As Integer Implements IVsHierarchy.GetSite Throw New NotImplementedException() End Function Public Function IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject3.IsDocumentInProject pfFound = 0 For Each kvp In _hierarchyItems If kvp.Value = pszMkDocument Then pfFound = 1 pitemid = kvp.Key Exit For End If Next Return VSConstants.S_OK End Function Public Function OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItem Throw New NotImplementedException() End Function Public Function OpenItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItemWithSpecific Throw New NotImplementedException() End Function Public Function ParseCanonicalName(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, ByRef pitemid As UInteger) As Integer Implements IVsHierarchy.ParseCanonicalName For Each kvp In _hierarchyItems If kvp.Value = pszName Then pitemid = kvp.Key Exit For End If Next Return VSConstants.S_OK End Function Public Function QueryClose(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanClose As Integer) As Integer Implements IVsHierarchy.QueryClose Throw New NotImplementedException() End Function Public Function RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject3.RemoveItem _hierarchyItems.Remove(itemid) Return VSConstants.S_OK End Function Public Function ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.ReopenItem Throw New NotImplementedException() End Function Public Function SetGuidProperty(itemid As UInteger, propid As Integer, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguid As Guid) As Integer Implements IVsHierarchy.SetGuidProperty Throw New NotImplementedException() End Function Public Function SetProperty(itemid As UInteger, propid As Integer, var As Object) As Integer Implements IVsHierarchy.SetProperty If propid = __VSHPROPID.VSHPROPID_ProjectName Then _projectName = If(TryCast(var, String), _projectName) Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function SetSite(psp As IServiceProvider) As Integer Implements IVsHierarchy.SetSite Throw New NotImplementedException() End Function Public Function TransferItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentOld As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentNew As String, punkWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.TransferItem For Each kvp In _hierarchyItems If kvp.Value = pszMkDocumentOld Then _hierarchyItems(kvp.Key) = pszMkDocumentNew Exit For End If Next Return VSConstants.S_OK End Function Public Function UnadviseHierarchyEvents(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> dwCookie As UInteger) As Integer Implements IVsHierarchy.UnadviseHierarchyEvents If Not _eventSinks.Remove(dwCookie) Then Throw New InvalidOperationException("The cookie was not subscribed.") End If Return VSConstants.S_OK End Function Public Function Unused0() As Integer Implements IVsHierarchy.Unused0 Throw New NotImplementedException() End Function Public Function Unused1() As Integer Implements IVsHierarchy.Unused1 Throw New NotImplementedException() End Function Public Function Unused2() As Integer Implements IVsHierarchy.Unused2 Throw New NotImplementedException() End Function Public Function Unused3() As Integer Implements IVsHierarchy.Unused3 Throw New NotImplementedException() End Function Public Function Unused4() As Integer Implements IVsHierarchy.Unused4 Throw New NotImplementedException() End Function Private Function IVsProject2_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject2.AddItem Throw New NotImplementedException() End Function Private Function IVsProject2_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject2.GenerateUniqueItemName Throw New NotImplementedException() End Function Private Function IVsProject2_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject2.GetItemContext Throw New NotImplementedException() End Function Private Function IVsProject2_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject2.GetMkDocument Throw New NotImplementedException() End Function Private Function IVsProject2_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject2.IsDocumentInProject Throw New NotImplementedException() End Function Private Function IVsProject2_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.OpenItem Throw New NotImplementedException() End Function Private Function IVsProject2_RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject2.RemoveItem Throw New NotImplementedException() End Function Private Function IVsProject2_ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.ReopenItem Throw New NotImplementedException() End Function Private Function IVsProject_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject.AddItem Throw New NotImplementedException() End Function Private Function IVsProject_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject.GenerateUniqueItemName Throw New NotImplementedException() End Function Private Function IVsProject_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject.GetItemContext Throw New NotImplementedException() End Function Private Function IVsProject_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject.GetMkDocument Throw New NotImplementedException() End Function Private Function IVsProject_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject.IsDocumentInProject Throw New NotImplementedException() End Function Private Function IVsProject_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject.OpenItem Throw New NotImplementedException() End Function Public Function SetInnerProject(punkInner As Object) As Integer Implements IVsAggregatableProject.SetInnerProject Throw New NotImplementedException() End Function Public Function InitializeForOuter(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszFilename As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszLocation As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCREATEPROJFLAGS")> grfCreateFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidProject As Guid, ByRef ppvProject As IntPtr, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanceled As Integer) As Integer Implements IVsAggregatableProject.InitializeForOuter Throw New NotImplementedException() End Function Public Function OnAggregationComplete() As Integer Implements IVsAggregatableProject.OnAggregationComplete Throw New NotImplementedException() End Function Public Function GetAggregateProjectTypeGuids(ByRef pbstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.GetAggregateProjectTypeGuids If _projectCapabilities = "VB" Then pbstrProjTypeGuids = Guids.VisualBasicProjectIdString Return VSConstants.S_OK ElseIf _projectCapabilities = "CSharp" Then pbstrProjTypeGuids = Guids.CSharpProjectIdString Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function SetAggregateProjectTypeGuids(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> lpstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.SetAggregateProjectTypeGuids Throw New NotImplementedException() End Function Public Function GetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, ByRef pbstrPropValue As String) As Integer Implements IVsBuildPropertyStorage.GetPropertyValue If pszPropName = "OutDir" Then pbstrPropValue = _projectBinPath Return VSConstants.S_OK ElseIf pszPropName = "TargetFileName" Then pbstrPropValue = PathUtilities.ChangeExtension(_projectName, "dll") Return VSConstants.S_OK ElseIf pszPropName = "TargetRefPath" Then pbstrPropValue = _projectRefPath Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then pbstrPropValue = _maxSupportedLangVer Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then pbstrPropValue = _runAnalyzers Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then pbstrPropValue = _runAnalyzersDuringLiveAnalysis Return VSConstants.S_OK End If Throw New NotSupportedException($"{NameOf(MockHierarchy)}.{NameOf(GetPropertyValue)} does not support reading {pszPropName}.") End Function Public Function SetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, pszPropValue As String) As Integer Implements IVsBuildPropertyStorage.SetPropertyValue If pszPropName = "OutDir" Then _projectBinPath = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = "TargetFileName" Then _projectName = PathUtilities.GetFileName(pszPropValue, includeExtension:=False) Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then _maxSupportedLangVer = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then _runAnalyzers = pszPropValue Return VSConstants.S_OK ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then _runAnalyzersDuringLiveAnalysis = pszPropValue Return VSConstants.S_OK End If Throw New NotImplementedException() End Function Public Function RemoveProperty(pszPropName As String, pszConfigName As String, storage As UInteger) As Integer Implements IVsBuildPropertyStorage.RemoveProperty Throw New NotImplementedException() End Function Public Function GetItemAttribute(item As UInteger, pszAttributeName As String, ByRef pbstrAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.GetItemAttribute Throw New NotImplementedException() End Function Public Function SetItemAttribute(item As UInteger, pszAttributeName As String, pszAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.SetItemAttribute Throw New NotImplementedException() End Function End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core.Wpf/Suggestions/AsyncSuggestedActionsSource.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnifiedSuggestions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class AsyncSuggestedActionsSource : SuggestedActionsSource, ISuggestedActionsSourceExperimental { public AsyncSuggestedActionsSource( IThreadingContext threadingContext, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry) : base(threadingContext, owner, textView, textBuffer, suggestedActionCategoryRegistry) { } public async IAsyncEnumerable<SuggestedActionSet> GetSuggestedActionsAsync( ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, [EnumeratorCancellation] CancellationToken cancellationToken) { AssertIsForeground(); using var state = SourceState.TryAddReference(); if (state is null) yield break; var workspace = state.Target.Workspace; if (workspace is null) yield break; var selection = TryGetCodeRefactoringSelection(state, range); await workspace.Services.GetRequiredService<IWorkspaceStatusService>().WaitUntilFullyLoadedAsync(cancellationToken).ConfigureAwait(false); using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActionsAsync, cancellationToken)) { var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) yield break; // Compute and return the high pri set of fixes and refactorings first so the user // can act on them immediately without waiting on the regular set. var highPriSet = GetCodeFixesAndRefactoringsAsync( state, requestedActionCategories, document, range, selection, _ => null, CodeActionRequestPriority.High, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false); await foreach (var set in highPriSet) yield return set; var lowPriSet = GetCodeFixesAndRefactoringsAsync( state, requestedActionCategories, document, range, selection, _ => null, CodeActionRequestPriority.Normal, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false); await foreach (var set in lowPriSet) yield return set; } } private async IAsyncEnumerable<SuggestedActionSet> GetCodeFixesAndRefactoringsAsync( ReferenceCountedDisposable<State> state, ISuggestedActionCategorySet requestedActionCategories, Document document, SnapshotSpan range, TextSpan? selection, Func<string, IDisposable?> addOperationScope, CodeActionRequestPriority priority, [EnumeratorCancellation] CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var supportsFeatureService = workspace.Services.GetRequiredService<ITextBufferSupportsFeatureService>(); var fixesTask = GetCodeFixesAsync( state, supportsFeatureService, requestedActionCategories, workspace, document, range, addOperationScope, priority, isBlocking: false, cancellationToken); var refactoringsTask = GetRefactoringsAsync( state, supportsFeatureService, requestedActionCategories, workspace, document, selection, addOperationScope, priority, isBlocking: false, cancellationToken); if (priority == CodeActionRequestPriority.High) { // in a high pri scenario, return data as soon as possible so that the user can interact with them. // this is especially important for state-machine oriented refactorings (like rename) where the user // should always have access to them effectively synchronously. var firstTask = await Task.WhenAny(fixesTask, refactoringsTask).ConfigureAwait(false); var secondTask = firstTask == fixesTask ? refactoringsTask : fixesTask; var orderedTasks = new[] { firstTask, secondTask }; foreach (var task in orderedTasks) { if (task == fixesTask) { var fixes = await fixesTask.ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes, ImmutableArray<UnifiedSuggestedActionSet>.Empty)) yield return set; } else { Contract.ThrowIfFalse(task == refactoringsTask); var refactorings = await refactoringsTask.ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, ImmutableArray<UnifiedSuggestedActionSet>.Empty, refactorings)) yield return set; } } } else { var actionsArray = await Task.WhenAll(fixesTask, refactoringsTask).ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes: actionsArray[0], refactorings: actionsArray[1])) yield return set; } } } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnifiedSuggestions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedActionsSourceProvider { private partial class AsyncSuggestedActionsSource : SuggestedActionsSource, ISuggestedActionsSourceExperimental { public AsyncSuggestedActionsSource( IThreadingContext threadingContext, SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry) : base(threadingContext, owner, textView, textBuffer, suggestedActionCategoryRegistry) { } public async IAsyncEnumerable<SuggestedActionSet> GetSuggestedActionsAsync( ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, [EnumeratorCancellation] CancellationToken cancellationToken) { AssertIsForeground(); using var state = SourceState.TryAddReference(); if (state is null) yield break; var workspace = state.Target.Workspace; if (workspace is null) yield break; var selection = TryGetCodeRefactoringSelection(state, range); await workspace.Services.GetRequiredService<IWorkspaceStatusService>().WaitUntilFullyLoadedAsync(cancellationToken).ConfigureAwait(false); using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActionsAsync, cancellationToken)) { var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) yield break; // Compute and return the high pri set of fixes and refactorings first so the user // can act on them immediately without waiting on the regular set. var highPriSet = GetCodeFixesAndRefactoringsAsync( state, requestedActionCategories, document, range, selection, _ => null, CodeActionRequestPriority.High, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false); await foreach (var set in highPriSet) yield return set; var lowPriSet = GetCodeFixesAndRefactoringsAsync( state, requestedActionCategories, document, range, selection, _ => null, CodeActionRequestPriority.Normal, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false); await foreach (var set in lowPriSet) yield return set; } } private async IAsyncEnumerable<SuggestedActionSet> GetCodeFixesAndRefactoringsAsync( ReferenceCountedDisposable<State> state, ISuggestedActionCategorySet requestedActionCategories, Document document, SnapshotSpan range, TextSpan? selection, Func<string, IDisposable?> addOperationScope, CodeActionRequestPriority priority, [EnumeratorCancellation] CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var supportsFeatureService = workspace.Services.GetRequiredService<ITextBufferSupportsFeatureService>(); var fixesTask = GetCodeFixesAsync( state, supportsFeatureService, requestedActionCategories, workspace, document, range, addOperationScope, priority, isBlocking: false, cancellationToken); var refactoringsTask = GetRefactoringsAsync( state, supportsFeatureService, requestedActionCategories, workspace, document, selection, addOperationScope, priority, isBlocking: false, cancellationToken); if (priority == CodeActionRequestPriority.High) { // in a high pri scenario, return data as soon as possible so that the user can interact with them. // this is especially important for state-machine oriented refactorings (like rename) where the user // should always have access to them effectively synchronously. var firstTask = await Task.WhenAny(fixesTask, refactoringsTask).ConfigureAwait(false); var secondTask = firstTask == fixesTask ? refactoringsTask : fixesTask; var orderedTasks = new[] { firstTask, secondTask }; foreach (var task in orderedTasks) { if (task == fixesTask) { var fixes = await fixesTask.ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes, ImmutableArray<UnifiedSuggestedActionSet>.Empty)) yield return set; } else { Contract.ThrowIfFalse(task == refactoringsTask); var refactorings = await refactoringsTask.ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, ImmutableArray<UnifiedSuggestedActionSet>.Empty, refactorings)) yield return set; } } } else { var actionsArray = await Task.WhenAll(fixesTask, refactoringsTask).ConfigureAwait(false); foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes: actionsArray[0], refactorings: actionsArray[1])) yield return set; } } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/Formatting/CSharpFormattingInteractionService.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { [ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared] internal partial class CSharpFormattingInteractionService : IFormattingInteractionService { // All the characters that might potentially trigger formatting when typed private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFormattingInteractionService() { } public bool SupportsFormatDocument => true; public bool SupportsFormatOnPaste => true; public bool SupportsFormatSelection => true; public bool SupportsFormatOnReturn => false; public bool SupportsFormattingOnTypedCharacter(Document document, char ch) { // Performance: This method checks several options to determine if we should do smart // indent, none of which are controlled by editorconfig. Instead of calling // document.GetOptionsAsync we can use the Workspace's global options and thus save the // work of attempting to read in the editorconfig file. var options = document.Project.Solution.Workspace.Options; var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart; // We consider the proper placement of a close curly or open curly when it is typed at // the start of the line to be a smart-indentation operation. As such, even if "format // on typing" is off, if "smart indent" is on, we'll still format this. (However, we // won't touch anything else in the block this close curly belongs to.). // // See extended comment in GetFormattingChangesAsync for more details on this. if (smartIndentOn) { if (ch == '{' || ch == '}') { return true; } } // If format-on-typing is not on, then we don't support formatting on any other characters. var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp); if (!autoFormattingOnTyping) { return false; } if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp)) { return false; } if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp)) { return false; } // don't auto format after these keys if smart indenting is not on. if ((ch == '#' || ch == 'n') && !smartIndentOn) { return false; } return _supportedChars.Contains(ch); } public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync( Document document, TextSpan? textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var span = textSpan ?? new TextSpan(0, root.FullSpan.Length); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span); var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false); } return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray(); } public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync( Document document, TextSpan textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan); var service = document.GetLanguageService<ISyntaxFormattingService>(); if (service == null) { return ImmutableArray<TextChange>.Empty; } var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() }; rules.AddRange(service.GetDefaultFormattingRules()); var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false); } return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray(); } private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret) { var workspace = document.Project.Solution.Workspace; var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>(); return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document)); } Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync( Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<TextChange>(); private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync( SyntaxToken token, CancellationToken cancellationToken) { // If the token is a ) we only want to format if it's the close paren // of a using statement. That way if we have nested usings, the inner // using will align with the outer one when the user types the close paren. if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement)) { return true; } // If the token is a : we only want to format if it's a labeled statement // or case. When the colon is typed we'll want ot immediately have those // statements snap to their appropriate indentation level. if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax)) { return true; } // Only format an { if it is the first token on a line. We don't want to // mess with it if it's inside a line. if (token.IsKind(SyntaxKind.OpenBraceToken)) { var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!token.IsFirstTokenOnLine(text)) { return true; } } return false; } public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync( Document document, char typedChar, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { // first, find the token user just typed. var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); if (token.IsMissing || !ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) || token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None)) { return ImmutableArray<TextChange>.Empty; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattingRules = GetFormattingRules(document, caretPosition, token); var service = document.GetLanguageService<ISyntaxFactsService>(); if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken)) { return ImmutableArray<TextChange>.Empty; } var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false); if (shouldNotFormat) { return ImmutableArray<TextChange>.Empty; } var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false); } // Do not attempt to format on open/close brace if autoformat on close brace feature is // off, instead just smart indent. // // We want this behavior because it's totally reasonable for a user to want to not have // on automatic formatting because they feel it is too aggressive. However, by default, // if you have smart-indentation on and are just hitting enter, you'll common have the // caret placed one indent higher than your current construct. For example, if you have: // // if (true) // $ <-- smart indent will have placed the caret here here. // // This is acceptable given that the user may want to just write a simple statement there. // However, if they start writing `{`, then things should snap over to be: // // if (true) // { // // Importantly, this is just an indentation change, no actual 'formatting' is done. We do // the same with close brace. If you have: // // if (...) // { // bad . ly ( for (mmated+code) ) ; // $ <-- smart indent will have placed the care here. // // If the user hits `}` then we will properly smart indent the `}` to match the `{`. // However, we won't touch any of the other code in that block, unlike if we were // formatting. var onlySmartIndent = (token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) || (token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options)); if (onlySmartIndent) { // if we're only doing smart indent, then ignore all edits to this token that occur before // the span of the token. They're irrelevant and may screw up other code the user doesn't // want touched. var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false); return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray(); } // if formatting range fails, do format token one at least var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false); if (changes.Length > 0) { return changes; } return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray(); } private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options) { // User does not want auto-formatting (either in general, or for close braces in // specific). So we only smart indent close braces when typed. return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) || !options.GetOption(FormattingOptions2.AutoFormattingOnTyping); } private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options) { // User does not want auto-formatting . So we only smart indent open braces when typed. // Note: there is no specific option for controlling formatting on open brace. So we // don't have the symmetry with OnlySmartIndentCloseBrace. return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping); } private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var position = Math.Max(0, caretPosition - 1); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia: true); return token; } private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formatter = CreateSmartTokenFormatter(options, formattingRules, root); var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false); return changes; } private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root) => new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root); private static async Task<ImmutableArray<TextChange>> FormatRangeAsync( Document document, OptionSet options, SyntaxToken endToken, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken) { if (!IsEndToken(endToken)) { return ImmutableArray<TextChange>.Empty; } var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken); if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2)) { return ImmutableArray<TextChange>.Empty; } if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2)) { return ImmutableArray<TextChange>.Empty; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root); var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken); return changes.ToImmutableArray(); } private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret) { // Typing introduces several challenges around formatting. // Historically we've shipped several triggers that cause formatting to happen directly while typing. // These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases. // However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete, // or may otherwise have syntax errors, and thus edits could have unintended consequences. // // Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more* // conservative and *less* willing willing to make edits to the tree. // The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way) // despite what the tree actually looks like. // // It's ok that this is only during formatting that is caused by an edit because that formatting happens // implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand // and can be more aggressive about what it's doing. // // // For example, say you have the following code. // // ```c# // class C // { // int P { get { return // } // ``` // // Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to: // // ```c# // class C // { // int P { get { return; // } // ``` // // During a normal format-document call, this is not what would happen. // Specifically, because the parser will consume the '}' into the accessor, // it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce: // // ```c# // class C // { // int P // { // get // { // return; // } // ``` // // Because it's ok for this to format in that fashion if format-document is invoked, // but should not happen during typing, we insert a specialized rule *only* during typing to try to control this. // During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line. // But that won't work since this span is not on a single line: // // ```c# // class C // { // int P { get [|{ return; // }|] // ``` // // So, during typing, if we see any parent block is incomplete, we'll assume that // all our parent blocks are incomplete and we will place the suppression span like so: // // ```c# // class C // { // int P { get [|{ return;|] // } // ``` // // This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios. if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken) { return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>(); } return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance); } private static bool IsEndToken(SyntaxToken endToken) { if (endToken.IsKind(SyntaxKind.OpenBraceToken)) { return false; } return true; } // We'll autoformat on n, t, e, only if they are the last character of the below // keywords. private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind) => typedChar switch { 'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword, 't' => kind == SyntaxKind.SelectKeyword, 'e' => kind == SyntaxKind.WhereKeyword, _ => true, }; private static bool IsInvalidTokenKind(SyntaxToken token) { // invalid token to be formatted return token.IsKind(SyntaxKind.None) || token.IsKind(SyntaxKind.EndOfDirectiveToken) || token.IsKind(SyntaxKind.EndOfFileToken); } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { [ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared] internal partial class CSharpFormattingInteractionService : IFormattingInteractionService { // All the characters that might potentially trigger formatting when typed private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFormattingInteractionService() { } public bool SupportsFormatDocument => true; public bool SupportsFormatOnPaste => true; public bool SupportsFormatSelection => true; public bool SupportsFormatOnReturn => false; public bool SupportsFormattingOnTypedCharacter(Document document, char ch) { // Performance: This method checks several options to determine if we should do smart // indent, none of which are controlled by editorconfig. Instead of calling // document.GetOptionsAsync we can use the Workspace's global options and thus save the // work of attempting to read in the editorconfig file. var options = document.Project.Solution.Workspace.Options; var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart; // We consider the proper placement of a close curly or open curly when it is typed at // the start of the line to be a smart-indentation operation. As such, even if "format // on typing" is off, if "smart indent" is on, we'll still format this. (However, we // won't touch anything else in the block this close curly belongs to.). // // See extended comment in GetFormattingChangesAsync for more details on this. if (smartIndentOn) { if (ch == '{' || ch == '}') { return true; } } // If format-on-typing is not on, then we don't support formatting on any other characters. var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp); if (!autoFormattingOnTyping) { return false; } if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp)) { return false; } if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp)) { return false; } // don't auto format after these keys if smart indenting is not on. if ((ch == '#' || ch == 'n') && !smartIndentOn) { return false; } return _supportedChars.Contains(ch); } public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync( Document document, TextSpan? textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var span = textSpan ?? new TextSpan(0, root.FullSpan.Length); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span); var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false); } return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray(); } public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync( Document document, TextSpan textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan); var service = document.GetLanguageService<ISyntaxFormattingService>(); if (service == null) { return ImmutableArray<TextChange>.Empty; } var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() }; rules.AddRange(service.GetDefaultFormattingRules()); var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false); } return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray(); } private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret) { var workspace = document.Project.Solution.Workspace; var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>(); return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document)); } Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync( Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<TextChange>(); private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync( SyntaxToken token, CancellationToken cancellationToken) { // If the token is a ) we only want to format if it's the close paren // of a using statement. That way if we have nested usings, the inner // using will align with the outer one when the user types the close paren. if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement)) { return true; } // If the token is a : we only want to format if it's a labeled statement // or case. When the colon is typed we'll want ot immediately have those // statements snap to their appropriate indentation level. if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax)) { return true; } // Only format an { if it is the first token on a line. We don't want to // mess with it if it's inside a line. if (token.IsKind(SyntaxKind.OpenBraceToken)) { var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!token.IsFirstTokenOnLine(text)) { return true; } } return false; } public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync( Document document, char typedChar, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken) { // first, find the token user just typed. var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); if (token.IsMissing || !ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) || token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None)) { return ImmutableArray<TextChange>.Empty; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattingRules = GetFormattingRules(document, caretPosition, token); var service = document.GetLanguageService<ISyntaxFactsService>(); if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken)) { return ImmutableArray<TextChange>.Empty; } var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false); if (shouldNotFormat) { return ImmutableArray<TextChange>.Empty; } var options = documentOptions; if (options == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>(); options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false); } // Do not attempt to format on open/close brace if autoformat on close brace feature is // off, instead just smart indent. // // We want this behavior because it's totally reasonable for a user to want to not have // on automatic formatting because they feel it is too aggressive. However, by default, // if you have smart-indentation on and are just hitting enter, you'll common have the // caret placed one indent higher than your current construct. For example, if you have: // // if (true) // $ <-- smart indent will have placed the caret here here. // // This is acceptable given that the user may want to just write a simple statement there. // However, if they start writing `{`, then things should snap over to be: // // if (true) // { // // Importantly, this is just an indentation change, no actual 'formatting' is done. We do // the same with close brace. If you have: // // if (...) // { // bad . ly ( for (mmated+code) ) ; // $ <-- smart indent will have placed the care here. // // If the user hits `}` then we will properly smart indent the `}` to match the `{`. // However, we won't touch any of the other code in that block, unlike if we were // formatting. var onlySmartIndent = (token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) || (token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options)); if (onlySmartIndent) { // if we're only doing smart indent, then ignore all edits to this token that occur before // the span of the token. They're irrelevant and may screw up other code the user doesn't // want touched. var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false); return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray(); } // if formatting range fails, do format token one at least var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false); if (changes.Length > 0) { return changes; } return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray(); } private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options) { // User does not want auto-formatting (either in general, or for close braces in // specific). So we only smart indent close braces when typed. return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) || !options.GetOption(FormattingOptions2.AutoFormattingOnTyping); } private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options) { // User does not want auto-formatting . So we only smart indent open braces when typed. // Note: there is no specific option for controlling formatting on open brace. So we // don't have the symmetry with OnlySmartIndentCloseBrace. return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping); } private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var position = Math.Max(0, caretPosition - 1); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia: true); return token; } private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formatter = CreateSmartTokenFormatter(options, formattingRules, root); var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false); return changes; } private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root) => new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root); private static async Task<ImmutableArray<TextChange>> FormatRangeAsync( Document document, OptionSet options, SyntaxToken endToken, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken) { if (!IsEndToken(endToken)) { return ImmutableArray<TextChange>.Empty; } var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken); if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2)) { return ImmutableArray<TextChange>.Empty; } if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2)) { return ImmutableArray<TextChange>.Empty; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root); var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken); return changes.ToImmutableArray(); } private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret) { // Typing introduces several challenges around formatting. // Historically we've shipped several triggers that cause formatting to happen directly while typing. // These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases. // However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete, // or may otherwise have syntax errors, and thus edits could have unintended consequences. // // Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more* // conservative and *less* willing willing to make edits to the tree. // The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way) // despite what the tree actually looks like. // // It's ok that this is only during formatting that is caused by an edit because that formatting happens // implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand // and can be more aggressive about what it's doing. // // // For example, say you have the following code. // // ```c# // class C // { // int P { get { return // } // ``` // // Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to: // // ```c# // class C // { // int P { get { return; // } // ``` // // During a normal format-document call, this is not what would happen. // Specifically, because the parser will consume the '}' into the accessor, // it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce: // // ```c# // class C // { // int P // { // get // { // return; // } // ``` // // Because it's ok for this to format in that fashion if format-document is invoked, // but should not happen during typing, we insert a specialized rule *only* during typing to try to control this. // During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line. // But that won't work since this span is not on a single line: // // ```c# // class C // { // int P { get [|{ return; // }|] // ``` // // So, during typing, if we see any parent block is incomplete, we'll assume that // all our parent blocks are incomplete and we will place the suppression span like so: // // ```c# // class C // { // int P { get [|{ return;|] // } // ``` // // This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios. if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken) { return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>(); } return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance); } private static bool IsEndToken(SyntaxToken endToken) { if (endToken.IsKind(SyntaxKind.OpenBraceToken)) { return false; } return true; } // We'll autoformat on n, t, e, only if they are the last character of the below // keywords. private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind) => typedChar switch { 'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword, 't' => kind == SyntaxKind.SelectKeyword, 'e' => kind == SyntaxKind.WhereKeyword, _ => true, }; private static bool IsInvalidTokenKind(SyntaxToken token) { // invalid token to be formatted return token.IsKind(SyntaxKind.None) || token.IsKind(SyntaxKind.EndOfDirectiveToken) || token.IsKind(SyntaxKind.EndOfFileToken); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/Core/Portable/Workspace/Solution/Checksum_Factory.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.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { // various factory methods. all these are just helper methods internal partial class Checksum { private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool = new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20); public static Checksum Create(IEnumerable<string> values) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; foreach (var value in values) { AppendData(hash, pooledBuffer.Object, value); AppendData(hash, pooledBuffer.Object, "\0"); } return From(hash.GetHashAndReset()); } public static Checksum Create(string value) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; AppendData(hash, pooledBuffer.Object, value); return From(hash.GetHashAndReset()); } public static Checksum Create(Stream stream) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; var buffer = pooledBuffer.Object; var bufferLength = buffer.Length; int bytesRead; do { bytesRead = stream.Read(buffer, 0, bufferLength); if (bytesRead > 0) { hash.AppendData(buffer, 0, bytesRead); } } while (bytesRead > 0); var bytes = hash.GetHashAndReset(); // if bytes array is bigger than certain size, checksum // will truncate it to predetermined size. for more detail, // see the Checksum type // // the truncation can happen since different hash algorithm or // same algorithm on different platform can have different hash size // which might be bigger than the Checksum HashSize. // // hash algorithm used here should remain functionally correct even // after the truncation return From(bytes); } public static Checksum Create(IObjectWritable @object) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { @object.WriteTo(objectWriter); } stream.Position = 0; return Create(stream); } public static Checksum Create(Checksum checksum1, Checksum checksum2) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { checksum1.WriteTo(writer); checksum2.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(Checksum checksum1, Checksum checksum2, Checksum checksum3) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { checksum1.WriteTo(writer); checksum2.WriteTo(writer); checksum3.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(IEnumerable<Checksum> checksums) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { foreach (var checksum in checksums) checksum.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(ImmutableArray<byte> bytes) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { for (var i = 0; i < bytes.Length; i++) writer.WriteByte(bytes[i]); } stream.Position = 0; return Create(stream); } public static Checksum Create<T>(T value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(value!, objectWriter, context, CancellationToken.None); } stream.Position = 0; return Create(stream); } public static Checksum Create(ParseOptions value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.SerializeParseOptions(value, objectWriter); } stream.Position = 0; return Create(stream); } private static void AppendData(IncrementalHash hash, byte[] buffer, string value) { var stringBytes = MemoryMarshal.AsBytes(value.AsSpan()); Debug.Assert(stringBytes.Length == value.Length * 2); var index = 0; while (index < stringBytes.Length) { var remaining = stringBytes.Length - index; var toCopy = Math.Min(remaining, buffer.Length); stringBytes.Slice(index, toCopy).CopyTo(buffer); hash.AppendData(buffer, 0, toCopy); index += toCopy; } } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { // various factory methods. all these are just helper methods internal partial class Checksum { private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool = new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20); public static Checksum Create(IEnumerable<string> values) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; foreach (var value in values) { AppendData(hash, pooledBuffer.Object, value); AppendData(hash, pooledBuffer.Object, "\0"); } return From(hash.GetHashAndReset()); } public static Checksum Create(string value) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; AppendData(hash, pooledBuffer.Object, value); return From(hash.GetHashAndReset()); } public static Checksum Create(Stream stream) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; var buffer = pooledBuffer.Object; var bufferLength = buffer.Length; int bytesRead; do { bytesRead = stream.Read(buffer, 0, bufferLength); if (bytesRead > 0) { hash.AppendData(buffer, 0, bytesRead); } } while (bytesRead > 0); var bytes = hash.GetHashAndReset(); // if bytes array is bigger than certain size, checksum // will truncate it to predetermined size. for more detail, // see the Checksum type // // the truncation can happen since different hash algorithm or // same algorithm on different platform can have different hash size // which might be bigger than the Checksum HashSize. // // hash algorithm used here should remain functionally correct even // after the truncation return From(bytes); } public static Checksum Create(IObjectWritable @object) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { @object.WriteTo(objectWriter); } stream.Position = 0; return Create(stream); } public static Checksum Create(Checksum checksum1, Checksum checksum2) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { checksum1.WriteTo(writer); checksum2.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(Checksum checksum1, Checksum checksum2, Checksum checksum3) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { checksum1.WriteTo(writer); checksum2.WriteTo(writer); checksum3.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(IEnumerable<Checksum> checksums) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { foreach (var checksum in checksums) checksum.WriteTo(writer); } stream.Position = 0; return Create(stream); } public static Checksum Create(ImmutableArray<byte> bytes) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { for (var i = 0; i < bytes.Length; i++) writer.WriteByte(bytes[i]); } stream.Position = 0; return Create(stream); } public static Checksum Create<T>(T value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(value!, objectWriter, context, CancellationToken.None); } stream.Position = 0; return Create(stream); } public static Checksum Create(ParseOptions value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.SerializeParseOptions(value, objectWriter); } stream.Position = 0; return Create(stream); } private static void AppendData(IncrementalHash hash, byte[] buffer, string value) { var stringBytes = MemoryMarshal.AsBytes(value.AsSpan()); Debug.Assert(stringBytes.Length == value.Length * 2); var index = 0; while (index < stringBytes.Length) { var remaining = stringBytes.Length - index; var toCopy = Math.Min(remaining, buffer.Length); stringBytes.Slice(index, toCopy).CopyTo(buffer); hash.AppendData(buffer, 0, toCopy); index += toCopy; } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private class State { public ImmutableArray<ConstructorCandidate> ConstructorCandidates { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public static async Task<State?> GenerateAsync( ImmutableArray<ISymbol> selectedMembers, Document document, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync( selectedMembers, document, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( ImmutableArray<ISymbol> selectedMembers, Document document, CancellationToken cancellationToken) { ContainingType = selectedMembers[0].ContainingType; var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); var parametersForSelectedMembers = DetermineParameters(selectedMembers, rules); if (!selectedMembers.All(IsWritableInstanceFieldOrProperty) || ContainingType == null || ContainingType.TypeKind == TypeKind.Interface || parametersForSelectedMembers.IsEmpty) { return false; } ConstructorCandidates = await GetConstructorCandidatesInfoAsync( ContainingType, selectedMembers, document, parametersForSelectedMembers, cancellationToken).ConfigureAwait(false); return !ConstructorCandidates.IsEmpty; } /// <summary> /// Try to find all constructors in <paramref name="containingType"/> whose parameters /// are a subset of the selected members by comparing name. /// These constructors will not be considered as potential candidates: /// - if the constructor's parameter list contains 'ref' or 'params' /// - any constructor that has a params[] parameter /// - deserialization constructor /// - implicit default constructor /// </summary> private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCandidatesInfoAsync( INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, Document document, ImmutableArray<IParameterSymbol> parametersForSelectedMembers, CancellationToken cancellationToken) { using var _ = ArrayBuilder<ConstructorCandidate>.GetInstance(out var applicableConstructors); foreach (var constructor in containingType.InstanceConstructors) { if (await IsApplicableConstructorAsync( constructor, document, parametersForSelectedMembers.SelectAsArray(p => p.Name), cancellationToken).ConfigureAwait(false)) { applicableConstructors.Add(CreateConstructorCandidate(parametersForSelectedMembers, selectedMembers, constructor)); } } return applicableConstructors.ToImmutable(); } private static async Task<bool> IsApplicableConstructorAsync(IMethodSymbol constructor, Document document, ImmutableArray<string> parameterNamesForSelectedMembers, CancellationToken cancellationToken) { var constructorParams = constructor.Parameters; if (constructorParams.Length == 2) { var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var deserializationConstructorCheck = new DeserializationConstructorCheck(compilation); if (deserializationConstructorCheck.IsDeserializationConstructor(constructor)) { return false; } } return constructorParams.All(parameter => parameter.RefKind == RefKind.None) && !constructor.IsImplicitlyDeclared && !constructorParams.Any(p => p.IsParams) && !SelectedMembersAlreadyExistAsParameters(parameterNamesForSelectedMembers, constructorParams); } private static bool SelectedMembersAlreadyExistAsParameters(ImmutableArray<string> parameterNamesForSelectedMembers, ImmutableArray<IParameterSymbol> constructorParams) => constructorParams.Length != 0 && !parameterNamesForSelectedMembers.Except(constructorParams.Select(p => p.Name)).Any(); private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IParameterSymbol> parametersForSelectedMembers, ImmutableArray<ISymbol> selectedMembers, IMethodSymbol constructor) { using var _0 = ArrayBuilder<IParameterSymbol>.GetInstance(out var missingParametersBuilder); using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var missingMembersBuilder); var constructorParamNames = constructor.Parameters.SelectAsArray(p => p.Name); var zippedParametersAndSelectedMembers = parametersForSelectedMembers.Zip(selectedMembers, (parameter, selectedMember) => (parameter, selectedMember)); foreach (var (parameter, selectedMember) in zippedParametersAndSelectedMembers) { if (!constructorParamNames.Contains(parameter.Name)) { missingParametersBuilder.Add(parameter); missingMembersBuilder.Add(selectedMember); } } return new ConstructorCandidate( constructor, missingMembersBuilder.ToImmutable(), missingParametersBuilder.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. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private class State { public ImmutableArray<ConstructorCandidate> ConstructorCandidates { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public static async Task<State?> GenerateAsync( ImmutableArray<ISymbol> selectedMembers, Document document, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync( selectedMembers, document, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( ImmutableArray<ISymbol> selectedMembers, Document document, CancellationToken cancellationToken) { ContainingType = selectedMembers[0].ContainingType; var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); var parametersForSelectedMembers = DetermineParameters(selectedMembers, rules); if (!selectedMembers.All(IsWritableInstanceFieldOrProperty) || ContainingType == null || ContainingType.TypeKind == TypeKind.Interface || parametersForSelectedMembers.IsEmpty) { return false; } ConstructorCandidates = await GetConstructorCandidatesInfoAsync( ContainingType, selectedMembers, document, parametersForSelectedMembers, cancellationToken).ConfigureAwait(false); return !ConstructorCandidates.IsEmpty; } /// <summary> /// Try to find all constructors in <paramref name="containingType"/> whose parameters /// are a subset of the selected members by comparing name. /// These constructors will not be considered as potential candidates: /// - if the constructor's parameter list contains 'ref' or 'params' /// - any constructor that has a params[] parameter /// - deserialization constructor /// - implicit default constructor /// </summary> private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCandidatesInfoAsync( INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, Document document, ImmutableArray<IParameterSymbol> parametersForSelectedMembers, CancellationToken cancellationToken) { using var _ = ArrayBuilder<ConstructorCandidate>.GetInstance(out var applicableConstructors); foreach (var constructor in containingType.InstanceConstructors) { if (await IsApplicableConstructorAsync( constructor, document, parametersForSelectedMembers.SelectAsArray(p => p.Name), cancellationToken).ConfigureAwait(false)) { applicableConstructors.Add(CreateConstructorCandidate(parametersForSelectedMembers, selectedMembers, constructor)); } } return applicableConstructors.ToImmutable(); } private static async Task<bool> IsApplicableConstructorAsync(IMethodSymbol constructor, Document document, ImmutableArray<string> parameterNamesForSelectedMembers, CancellationToken cancellationToken) { var constructorParams = constructor.Parameters; if (constructorParams.Length == 2) { var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var deserializationConstructorCheck = new DeserializationConstructorCheck(compilation); if (deserializationConstructorCheck.IsDeserializationConstructor(constructor)) { return false; } } return constructorParams.All(parameter => parameter.RefKind == RefKind.None) && !constructor.IsImplicitlyDeclared && !constructorParams.Any(p => p.IsParams) && !SelectedMembersAlreadyExistAsParameters(parameterNamesForSelectedMembers, constructorParams); } private static bool SelectedMembersAlreadyExistAsParameters(ImmutableArray<string> parameterNamesForSelectedMembers, ImmutableArray<IParameterSymbol> constructorParams) => constructorParams.Length != 0 && !parameterNamesForSelectedMembers.Except(constructorParams.Select(p => p.Name)).Any(); private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IParameterSymbol> parametersForSelectedMembers, ImmutableArray<ISymbol> selectedMembers, IMethodSymbol constructor) { using var _0 = ArrayBuilder<IParameterSymbol>.GetInstance(out var missingParametersBuilder); using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var missingMembersBuilder); var constructorParamNames = constructor.Parameters.SelectAsArray(p => p.Name); var zippedParametersAndSelectedMembers = parametersForSelectedMembers.Zip(selectedMembers, (parameter, selectedMember) => (parameter, selectedMember)); foreach (var (parameter, selectedMember) in zippedParametersAndSelectedMembers) { if (!constructorParamNames.Contains(parameter.Name)) { missingParametersBuilder.Add(parameter); missingMembersBuilder.Add(selectedMember); } } return new ConstructorCandidate( constructor, missingMembersBuilder.ToImmutable(), missingParametersBuilder.ToImmutable()); } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/BoolKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class BoolKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public BoolKeywordRecommender() : base(SyntaxKind.BoolKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Boolean; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class BoolKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public BoolKeywordRecommender() : base(SyntaxKind.BoolKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Boolean; } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./eng/common/init-tools-native.ps1
<# .SYNOPSIS Entry point script for installing native tools .DESCRIPTION Reads $RepoRoot\global.json file to determine native assets to install and executes installers for those tools .PARAMETER BaseUri Base file directory or Url from which to acquire tool archives .PARAMETER InstallDirectory Directory to install native toolset. This is a command-line override for the default Install directory precedence order: - InstallDirectory command-line override - NETCOREENG_INSTALL_DIRECTORY environment variable - (default) %USERPROFILE%/.netcoreeng/native .PARAMETER Clean Switch specifying to not install anything, but cleanup native asset folders .PARAMETER Force Clean and then install tools .PARAMETER DownloadRetries Total number of retry attempts .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds .PARAMETER GlobalJsonFile File path to global.json file .NOTES #> [CmdletBinding(PositionalBinding=$false)] Param ( [string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external', [string] $InstallDirectory, [switch] $Clean = $False, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [string] $GlobalJsonFile ) if (!$GlobalJsonFile) { $GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json' } Set-StrictMode -version 2.0 $ErrorActionPreference='Stop' . $PSScriptRoot\pipeline-logging-functions.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') try { # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq 'Continue' $EngCommonBaseDir = Join-Path $PSScriptRoot 'native\' $NativeBaseDir = $InstallDirectory if (!$NativeBaseDir) { $NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory } $Env:CommonLibrary_NativeInstallDir = $NativeBaseDir $InstallBin = Join-Path $NativeBaseDir 'bin' $InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1' # Process tools list Write-Host "Processing $GlobalJsonFile" If (-Not (Test-Path $GlobalJsonFile)) { Write-Host "Unable to find '$GlobalJsonFile'" exit 0 } $NativeTools = Get-Content($GlobalJsonFile) -Raw | ConvertFrom-Json | Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue if ($NativeTools) { $NativeTools.PSObject.Properties | ForEach-Object { $ToolName = $_.Name $ToolVersion = $_.Value $LocalInstallerArguments = @{ ToolName = "$ToolName" } $LocalInstallerArguments += @{ InstallPath = "$InstallBin" } $LocalInstallerArguments += @{ BaseUri = "$BaseUri" } $LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" } $LocalInstallerArguments += @{ Version = "$ToolVersion" } if ($Verbose) { $LocalInstallerArguments += @{ Verbose = $True } } if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') { if($Force) { $LocalInstallerArguments += @{ Force = $True } } } if ($Clean) { $LocalInstallerArguments += @{ Clean = $True } } Write-Verbose "Installing $ToolName version $ToolVersion" Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'" & $InstallerPath @LocalInstallerArguments if ($LASTEXITCODE -Ne "0") { $errMsg = "$ToolName installation failed" if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) { $showNativeToolsWarning = $true if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) { $showNativeToolsWarning = $false } if ($showNativeToolsWarning) { Write-Warning $errMsg } $toolInstallationFailure = $true } else { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host $errMsg exit 1 } } } if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host 'Native tools bootstrap failed' exit 1 } } else { Write-Host 'No native tools defined in global.json' exit 0 } if ($Clean) { exit 0 } if (Test-Path $InstallBin) { Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin) Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)" return $InstallBin } else { Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed' exit 1 } exit 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_ ExitWithExitCode 1 }
<# .SYNOPSIS Entry point script for installing native tools .DESCRIPTION Reads $RepoRoot\global.json file to determine native assets to install and executes installers for those tools .PARAMETER BaseUri Base file directory or Url from which to acquire tool archives .PARAMETER InstallDirectory Directory to install native toolset. This is a command-line override for the default Install directory precedence order: - InstallDirectory command-line override - NETCOREENG_INSTALL_DIRECTORY environment variable - (default) %USERPROFILE%/.netcoreeng/native .PARAMETER Clean Switch specifying to not install anything, but cleanup native asset folders .PARAMETER Force Clean and then install tools .PARAMETER DownloadRetries Total number of retry attempts .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds .PARAMETER GlobalJsonFile File path to global.json file .NOTES #> [CmdletBinding(PositionalBinding=$false)] Param ( [string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external', [string] $InstallDirectory, [switch] $Clean = $False, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [string] $GlobalJsonFile ) if (!$GlobalJsonFile) { $GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json' } Set-StrictMode -version 2.0 $ErrorActionPreference='Stop' . $PSScriptRoot\pipeline-logging-functions.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') try { # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq 'Continue' $EngCommonBaseDir = Join-Path $PSScriptRoot 'native\' $NativeBaseDir = $InstallDirectory if (!$NativeBaseDir) { $NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory } $Env:CommonLibrary_NativeInstallDir = $NativeBaseDir $InstallBin = Join-Path $NativeBaseDir 'bin' $InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1' # Process tools list Write-Host "Processing $GlobalJsonFile" If (-Not (Test-Path $GlobalJsonFile)) { Write-Host "Unable to find '$GlobalJsonFile'" exit 0 } $NativeTools = Get-Content($GlobalJsonFile) -Raw | ConvertFrom-Json | Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue if ($NativeTools) { $NativeTools.PSObject.Properties | ForEach-Object { $ToolName = $_.Name $ToolVersion = $_.Value $LocalInstallerArguments = @{ ToolName = "$ToolName" } $LocalInstallerArguments += @{ InstallPath = "$InstallBin" } $LocalInstallerArguments += @{ BaseUri = "$BaseUri" } $LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" } $LocalInstallerArguments += @{ Version = "$ToolVersion" } if ($Verbose) { $LocalInstallerArguments += @{ Verbose = $True } } if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') { if($Force) { $LocalInstallerArguments += @{ Force = $True } } } if ($Clean) { $LocalInstallerArguments += @{ Clean = $True } } Write-Verbose "Installing $ToolName version $ToolVersion" Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'" & $InstallerPath @LocalInstallerArguments if ($LASTEXITCODE -Ne "0") { $errMsg = "$ToolName installation failed" if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) { $showNativeToolsWarning = $true if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) { $showNativeToolsWarning = $false } if ($showNativeToolsWarning) { Write-Warning $errMsg } $toolInstallationFailure = $true } else { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host $errMsg exit 1 } } } if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host 'Native tools bootstrap failed' exit 1 } } else { Write-Host 'No native tools defined in global.json' exit 0 } if ($Clean) { exit 0 } if (Test-Path $InstallBin) { Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin) Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)" return $InstallBin } else { Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed' exit 1 } exit 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/Embed.vbproj
<?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></ProductVersion> <SchemaVersion></SchemaVersion> <ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>VisualBasicProject</RootNamespace> <AssemblyName>VisualBasicProject</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <VBRuntime>Embed</VBRuntime> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> <RemoveIntegerChecks>true</RemoveIntegerChecks> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> <DefineConstants>FURBY</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>Off</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> <Import Include="System.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <Compile Include="VisualBasicClass.vb" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CSharpProject\CSharpProject.csproj"> <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project> <Name>CSharpProject</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.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></ProductVersion> <SchemaVersion></SchemaVersion> <ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>VisualBasicProject</RootNamespace> <AssemblyName>VisualBasicProject</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <VBRuntime>Embed</VBRuntime> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> <RemoveIntegerChecks>true</RemoveIntegerChecks> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> <DefineConstants>FURBY</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>Off</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> <Import Include="System.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <Compile Include="VisualBasicClass.vb" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CSharpProject\CSharpProject.csproj"> <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project> <Name>CSharpProject</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.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,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { /// <summary> /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token. /// </summary> /// <param name="semanticModel">The SemanticModel object to get semantic information /// from.</param> /// <param name="token">The token to get semantic information from. This must be part of the /// syntax tree associated with the binding.</param> /// <param name="cancellationToken">A cancellation token.</param> public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => semanticModel.GetSymbolInfo(token.Parent!, cancellationToken); public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken) { return semanticModel.GetDeclaredSymbol(declaration, cancellationToken) ?? throw new InvalidOperationException(); } public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol(position, cancellationToken) ?? throw new InvalidOperationException(); } public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : class, ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol tSymbol) { return tSymbol; } } return null; } public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ?? (ISymbol)semanticModel.Compilation.Assembly; } public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken); public static IEnumerable<ISymbol> GetExistingSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { // Ignore an anonymous type property or tuple field. It's ok if they have a name that // matches the name of the local we're introducing. return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto) .Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField()); } public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel) { if (!semanticModel.IsSpeculativeSemanticModel) { return semanticModel; } Contract.ThrowIfNull(semanticModel.ParentModel); Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel); Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null); return semanticModel.ParentModel; } public static HashSet<ISymbol> GetAllDeclaredSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null) { var symbols = new HashSet<ISymbol>(); if (container != null) { GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter); } return symbols; } private static void GetAllDeclaredSymbols( SemanticModel semanticModel, SyntaxNode node, HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol != null) { symbols.Add(symbol); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { var childNode = child.AsNode()!; if (ShouldDescendInto(childNode, descendInto)) { GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto); } } } static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter) => filter != null ? filter(node) : true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { /// <summary> /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token. /// </summary> /// <param name="semanticModel">The SemanticModel object to get semantic information /// from.</param> /// <param name="token">The token to get semantic information from. This must be part of the /// syntax tree associated with the binding.</param> /// <param name="cancellationToken">A cancellation token.</param> public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => semanticModel.GetSymbolInfo(token.Parent!, cancellationToken); public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken) { return semanticModel.GetDeclaredSymbol(declaration, cancellationToken) ?? throw new InvalidOperationException(); } public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol(position, cancellationToken) ?? throw new InvalidOperationException(); } public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : class, ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol tSymbol) { return tSymbol; } } return null; } public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ?? (ISymbol)semanticModel.Compilation.Assembly; } public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken); public static IEnumerable<ISymbol> GetExistingSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { // Ignore an anonymous type property or tuple field. It's ok if they have a name that // matches the name of the local we're introducing. return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto) .Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField()); } public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel) { if (!semanticModel.IsSpeculativeSemanticModel) { return semanticModel; } Contract.ThrowIfNull(semanticModel.ParentModel); Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel); Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null); return semanticModel.ParentModel; } public static HashSet<ISymbol> GetAllDeclaredSymbols( this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null) { var symbols = new HashSet<ISymbol>(); if (container != null) { GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter); } return symbols; } private static void GetAllDeclaredSymbols( SemanticModel semanticModel, SyntaxNode node, HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol != null) { symbols.Add(symbol); } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { var childNode = child.AsNode()!; if (ShouldDescendInto(childNode, descendInto)) { GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto); } } } static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter) => filter != null ? filter(node) : true; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Shared/Utilities/ForegroundThreadAffinitizedObject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { /// <summary> /// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or /// a background thread. It also allows scheduling work to the foreground thread at below input priority. /// </summary> internal class ForegroundThreadAffinitizedObject { private readonly IThreadingContext _threadingContext; internal IThreadingContext ThreadingContext => _threadingContext; public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false) { _threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext)); // ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread. // AssertIsForeground here only if the object must be created on a foreground thread. if (assertIsForeground) { // Assert we have some kind of foreground thread Contract.ThrowIfFalse(threadingContext.HasMainThread); AssertIsForeground(); } } public bool IsForeground() => _threadingContext.JoinableTaskContext.IsOnMainThread; public void AssertIsForeground() { var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread; var currentThread = Thread.CurrentThread; // In debug, provide a lot more information so that we can track down unit test flakiness. // This is too expensive to do in retail as it creates way too many allocations. Debug.Assert(currentThread == whenCreatedThread, "When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" + "When created thread name: " + whenCreatedThread?.Name + "\r\n" + "Current thread id : " + currentThread?.ManagedThreadId + "\r\n" + "Current thread name : " + currentThread?.Name); // But, in retail, do the check as well, so that we can catch problems that happen in the wild. Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread); } public void AssertIsBackground() => Contract.ThrowIfTrue(IsForeground()); /// <summary> /// A helpful marker method that can be used by deriving classes to indicate that a /// method can be called from any thread and is not foreground or background affinitized. /// This is useful so that every method in deriving class can have some sort of marker /// on each method stating the threading constraints (FG-only/BG-only/Any-thread). /// </summary> public static void ThisCanBeCalledOnAnyThread() { // Does nothing. } public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default) { if (IsForeground() && !IsInputPending()) { // Optimize to inline the action if we're already on the foreground thread // and there's no pending user input. action(); return Task.CompletedTask; } else { return Task.Factory.SafeStartNewFromAsync( async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); action(); }, cancellationToken, TaskScheduler.Default); } } /// <summary> /// Returns true if any keyboard or mouse button input is pending on the message queue. /// </summary> protected static bool IsInputPending() { // The code below invokes into user32.dll, which is not available in non-Windows. if (PlatformInformation.IsUnix) { return false; } // The return value of GetQueueStatus is HIWORD:LOWORD. // A non-zero value in HIWORD indicates some input message in the queue. var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT); const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16); return (result & InputMask) != 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. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { /// <summary> /// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or /// a background thread. It also allows scheduling work to the foreground thread at below input priority. /// </summary> internal class ForegroundThreadAffinitizedObject { private readonly IThreadingContext _threadingContext; internal IThreadingContext ThreadingContext => _threadingContext; public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false) { _threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext)); // ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread. // AssertIsForeground here only if the object must be created on a foreground thread. if (assertIsForeground) { // Assert we have some kind of foreground thread Contract.ThrowIfFalse(threadingContext.HasMainThread); AssertIsForeground(); } } public bool IsForeground() => _threadingContext.JoinableTaskContext.IsOnMainThread; public void AssertIsForeground() { var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread; var currentThread = Thread.CurrentThread; // In debug, provide a lot more information so that we can track down unit test flakiness. // This is too expensive to do in retail as it creates way too many allocations. Debug.Assert(currentThread == whenCreatedThread, "When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" + "When created thread name: " + whenCreatedThread?.Name + "\r\n" + "Current thread id : " + currentThread?.ManagedThreadId + "\r\n" + "Current thread name : " + currentThread?.Name); // But, in retail, do the check as well, so that we can catch problems that happen in the wild. Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread); } public void AssertIsBackground() => Contract.ThrowIfTrue(IsForeground()); /// <summary> /// A helpful marker method that can be used by deriving classes to indicate that a /// method can be called from any thread and is not foreground or background affinitized. /// This is useful so that every method in deriving class can have some sort of marker /// on each method stating the threading constraints (FG-only/BG-only/Any-thread). /// </summary> public static void ThisCanBeCalledOnAnyThread() { // Does nothing. } public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default) { if (IsForeground() && !IsInputPending()) { // Optimize to inline the action if we're already on the foreground thread // and there's no pending user input. action(); return Task.CompletedTask; } else { return Task.Factory.SafeStartNewFromAsync( async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); action(); }, cancellationToken, TaskScheduler.Default); } } /// <summary> /// Returns true if any keyboard or mouse button input is pending on the message queue. /// </summary> protected static bool IsInputPending() { // The code below invokes into user32.dll, which is not available in non-Windows. if (PlatformInformation.IsUnix) { return false; } // The return value of GetQueueStatus is HIWORD:LOWORD. // A non-zero value in HIWORD indicates some input message in the queue. var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT); const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16); return (result & InputMask) != 0; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/CodeAnalysisTest/Collections/TestExtensionsMethods.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal static partial class TestExtensionsMethods { internal static void ValidateDefaultThisBehavior(Action a) { Assert.Throws<NullReferenceException>(a); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal static partial class TestExtensionsMethods { internal static void ValidateDefaultThisBehavior(Action a) { Assert.Throws<NullReferenceException>(a); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Test/Resources/Core/SymbolsTests/CorLibrary/GuidTest2.exe
MZ@ !L!This program cannot be run in DOS mode. $PELyL n# @@ @#O@`  H.textt  `.rsrc@@@.reloc ` @BP#Hp 0  o &*( *BSJB v4.0.30319l#~#StringsH#USP#GUID`L#BlobG %3 0)bBB )P 7 g <<<! <. !.*  <Module>GuidTest2.exeProgrammscorlibSystemObjectMain.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeGuidTest2GuidTest1I1GuidTest ~B 5z\V4   TWrapNonExceptionThrowsD#^# P#_CorExeMainmscoree.dll% @ 8Ph@LBL4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0<InternalNameGuidTest2.exe(LegalCopyright DOriginalFilenameGuidTest2.exe4ProductVersion0.0.0.08Assembly Version0.0.0.0<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> p3
MZ@ !L!This program cannot be run in DOS mode. $PELyL n# @@ @#O@`  H.textt  `.rsrc@@@.reloc ` @BP#Hp 0  o &*( *BSJB v4.0.30319l#~#StringsH#USP#GUID`L#BlobG %3 0)bBB )P 7 g <<<! <. !.*  <Module>GuidTest2.exeProgrammscorlibSystemObjectMain.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeGuidTest2GuidTest1I1GuidTest ~B 5z\V4   TWrapNonExceptionThrowsD#^# P#_CorExeMainmscoree.dll% @ 8Ph@LBL4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0<InternalNameGuidTest2.exe(LegalCopyright DOriginalFilenameGuidTest2.exe4ProductVersion0.0.0.08Assembly Version0.0.0.0<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> p3
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NamedAndOptionalTests : CompilingTestBase { [Fact] public void Test13984() { string source = @" using System; class Program { static void Main() { } static void M(DateTime da = new DateTime(2012, 6, 22), decimal d = new decimal(5), int i = new int()) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,33): error CS1736: Default parameter value for 'da' must be a compile-time constant // static void M(DateTime da = new DateTime(2012, 6, 22), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new DateTime(2012, 6, 22)").WithArguments("da"), // (7,31): error CS1736: Default parameter value for 'd' must be a compile-time constant // decimal d = new decimal(5), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new decimal(5)").WithArguments("d")); } [Fact] public void Test13861() { // * There are two decimal constant attribute constructors; we should honour both of them. // * Using named arguments to re-order the arguments must not change the value of the constant. string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { public static void Goo1([Optional][DecimalConstant(0, 0, low: (uint)100, mid: (uint)0, hi: (uint)0)] decimal i) { System.Console.Write(i); } public static void Goo2([Optional][DecimalConstant(0, 0, 0, 0, 200)] decimal i) { System.Console.Write(i); } static void Main(string[] args) { Goo1(); Goo2(); } }"; string expected = "100200"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsInCtors() { string source = @" class Alpha { public Alpha(int x = 123) { } } class Bravo : Alpha { // See bug 7846. // This should be legal; the generated ctor for Bravo should call base(123) } class Charlie : Alpha { public Charlie() : base() {} // This should be legal; should call base(123) } class Delta : Alpha { public Delta() {} // This should be legal; should call base(123) } abstract class Echo { protected Echo(int x = 123) {} } abstract class Foxtrot : Echo { } abstract class Hotel : Echo { protected Hotel() {} } abstract class Golf : Echo { protected Golf() : base() {} } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestNamedAndOptionalParamsErrors() { string source = @" class Base { public virtual void Goo(int reqParam1, int optParam1 = 0, int optParam2 = default(int), int optParam3 = new int(), string optParam4 = null, double optParam5 = 128L) { } } class Middle : Base { //override and change the parameters names public override void Goo(int reqChParam1, int optChParam1 = 0, int optChParam2 = default(int), int optChParam3 = new int(), string optChParam4 = null, double optChParam5 = 128L) { } } class C : Middle { public void Q(params int[] x) {} public void M() { var c = new C(); // calling child class parameters with base names // error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3' c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111); // error CS1738: Named argument specifications must appear after all fixed arguments have been specified c.Goo(optArg1: 3333, 11111); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (37,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3' // c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111); Diagnostic(ErrorCode.ERR_BadNamedArgument, "optParam3").WithArguments("Goo", "optParam3").WithLocation(37, 15), // (39,30): 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.Goo(optArg1: 3333, 11111); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "11111").WithArguments("7.2").WithLocation(39, 30), // (39,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optArg1' // c.Goo(optArg1: 3333, 11111); Diagnostic(ErrorCode.ERR_BadNamedArgument, "optArg1").WithArguments("Goo", "optArg1").WithLocation(39, 15) ); } [Fact] public void TestNamedAndOptionalParamsErrors2() { string source = @" class C { //error CS1736 public void M(string s = new string('c',5)) {} }"; CreateCompilation(source).VerifyDiagnostics( // (5,30): error CS1736: Default parameter value for 's' must be a compile-time constant // public void M(string s = new string('c',5)) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new string('c',5)").WithArguments("s").WithLocation(5, 30)); } [Fact] public void TestNamedAndOptionalParamsErrors3() { // Here we cannot report that "no overload of M takes two arguments" because of course // M(1, 2) is legal. We cannot report that any argument does not correspond to a formal; // all of them do. We cannot report that named arguments precede positional arguments. // We cannot report that any argument is not convertible to its corresponding formal; // all of them are convertible. The only error we can report here is that a formal // parameter has no corresponding argument. string source = @" class C { // CS7036 (ERR_NoCorrespondingArgument) delegate void F(int fx, int fg, int fz = 123); C(int cx, int cy, int cz = 123) {} public static void M(int mx, int my, int mz = 123) { F f = null; f(0, fz : 456); M(0, mz : 456); new C(0, cz : 456); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'fg' of 'C.F' // f(0, fz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "f").WithArguments("fg", "C.F").WithLocation(10, 9), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'my' of 'C.M(int, int, int)' // M(0, mz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("my", "C.M(int, int, int)").WithLocation(11, 9), // (12,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'cy' of 'C.C(int, int, int)' // new C(0, cz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("cy", "C.C(int, int, int)").WithLocation(12, 13)); } [Fact] public void TestNamedAndOptionalParamsCrazy() { // This was never supposed to work and the spec does not require it, but // nevertheless, the native compiler allows this: const string source = @" class C { static void C(int q = 10, params int[] x) {} static int X() { return 123; } static int Q() { return 345; } static void M() { C(x:X(), q:Q()); } }"; // and so Roslyn does too. It seems likely that someone has taken a dependency // on the bad pattern. CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type // static void C(int q = 10, params int[] x) {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15)); } [Fact] public void TestNamedAndOptionalParamsCrazyError() { // Fortunately, however, this is still illegal: const string source = @" class C { static void C(int q = 10, params int[] x) {} static void M() { C(1, 2, 3, x:4); } }"; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type // static void C(int q = 10, params int[] x) {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15), // (7,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // C(1, 2, 3, x:4); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(7, 16)); } [Fact] public void TestNamedAndOptionalParamsBasic() { string source = @" using System; public enum E { zero, one, two, three } public enum ELong : long { zero, one, two, three } public class EnumDefaultValues { public static void Run() { var x = new EnumDefaultValues(); x.M(); } void M( E e1 = 0, E e2 = default(E), E e3 = E.zero, E e4 = E.one, E? ne1 = 0, E? ne2 = default(E), E? ne3 = E.zero, E? ne4 = E.one, E? ne5 = null, E? ne6 = default(E?), ELong el1 = 0, ELong el2 = default(ELong), ELong el3 = ELong.zero, ELong el4 = ELong.one, ELong? nel1 = 0, ELong? nel2 = default(ELong), ELong? nel3 = ELong.zero, ELong? nel4 = ELong.one, ELong? nel5 = null, ELong? nel6 = default(ELong?) ) { Show(e1); Show(e2); Show(e3); Show(e4); Show(ne1); Show(ne2); Show(ne3); Show(ne4); Show(ne5); Show(ne6); Show(el1); Show(el2); Show(el3); Show(el4); Show(nel1); Show(nel2); Show(nel3); Show(nel4); Show(nel5); Show(nel6); } static void Show<T>(T t) { object o = t; Console.WriteLine(""{0}: {1}"", typeof(T), o != null ? o : ""<null>""); } } struct Sierra { public Alpha alpha; public Bravo bravo; public int i; public Sierra(Alpha alpha, Bravo bravo, int i) { this.alpha = alpha; this.bravo = bravo; this.i = i; } } class Alpha { public virtual int Mike(int xray) { return xray; } } class Bravo : Alpha { public override int Mike(int yankee) { return yankee; } } class Charlie : Bravo { void Foxtrot( int xray = 10, string yankee = ""sam"") { Console.WriteLine(""Foxtrot: xray={0} yankee={1}"", xray, yankee); } void Quebec( int xray, int yankee = 10, int zulu = 11) { Console.WriteLine(""Quebec: xray={0} yankee={1} zulu={2}"", xray, yankee, zulu); } void OutRef( out int xray, ref int yankee) { xray = 0; yankee = 0; } void ParamArray(params int[] xray) { Console.WriteLine(""ParamArray: xray={0}"", string.Join<int>("","", xray)); } void ParamArray2( int yankee = 10, params int[] xray) { Console.WriteLine(""ParamArray2: yankee={0} xray={1}"", yankee, string.Join<int>("","", xray)); } void Zeros( int xray = 0, int? yankee = 0, int? zulu = null, Charlie charlie = null) { Console.WriteLine(""Zeros: xray={0} yankee={1} zulu={2} charlie={3}"", xray, yankee == null ? ""null"" : yankee.ToString(), zulu == null ? ""null"" : zulu.ToString(), charlie == null ? ""null"" : charlie.ToString() ); } void OtherDefaults( string str = default(string), Alpha alpha = default(Alpha), Bravo bravo = default(Bravo), int i = default(int), Sierra sierra = default(Sierra)) { Console.WriteLine(""OtherDefaults: str={0} alpha={1} bravo={2} i={3} sierra={4}"", str == null ? ""null"" : str, alpha == null ? ""null"" : alpha.ToString(), bravo == null ? ""null"" : bravo.ToString(), i, sierra.alpha == null && sierra.bravo == null && sierra.i == 0 ? ""default(Sierra)"" : sierra.ToString()); } int Bar() { Console.WriteLine(""Bar""); return 96; } string Baz() { Console.WriteLine(""Baz""); return ""Baz""; } void BasicOptionalTests() { Console.WriteLine(""BasicOptional""); Foxtrot(0); Foxtrot(); ParamArray(1, 2, 3); Zeros(); OtherDefaults(); } void BasicNamedTests() { Console.WriteLine(""BasicNamed""); // Basic named test. Foxtrot(yankee: ""test"", xray: 1); Foxtrot(xray: 1, yankee: ""test""); // Test to see which execution comes first. Foxtrot(yankee: Baz(), xray: Bar()); int y = 100; int x = 100; OutRef(yankee: ref y, xray: out x); Console.WriteLine(x); Console.WriteLine(y); Charlie c = new Charlie(); ParamArray(xray: 1); ParamArray(xray: new int[] { 1, 2, 3 }); ParamArray2(xray: 1); ParamArray2(xray: new int[] { 1, 2, 3 }); ParamArray2(xray: 1, yankee: 20); ParamArray2(xray: new int[] { 1, 2, 3 }, yankee: 20); ParamArray2(); } void BasicNamedAndOptionalTests() { Console.WriteLine(""BasicNamedAndOptional""); Foxtrot(yankee: ""test""); Foxtrot(xray: 0); Quebec(1, yankee: 1); Quebec(1, zulu: 10); } void OverrideTest() { Console.WriteLine(Mike(yankee: 10)); } void TypeParamTest<T>() where T : Bravo, new() { T t = new T(); Console.WriteLine(t.Mike(yankee: 4)); } static void Main() { Charlie c = new Charlie(); c.BasicOptionalTests(); c.BasicNamedTests(); c.BasicNamedAndOptionalTests(); c.OverrideTest(); c.TypeParamTest<Bravo>(); EnumDefaultValues.Run(); } } "; string expected = @"BasicOptional Foxtrot: xray=0 yankee=sam Foxtrot: xray=10 yankee=sam ParamArray: xray=1,2,3 Zeros: xray=0 yankee=0 zulu=null charlie=null OtherDefaults: str=null alpha=null bravo=null i=0 sierra=default(Sierra) BasicNamed Foxtrot: xray=1 yankee=test Foxtrot: xray=1 yankee=test Baz Bar Foxtrot: xray=96 yankee=Baz 0 0 ParamArray: xray=1 ParamArray: xray=1,2,3 ParamArray2: yankee=10 xray=1 ParamArray2: yankee=10 xray=1,2,3 ParamArray2: yankee=20 xray=1 ParamArray2: yankee=20 xray=1,2,3 ParamArray2: yankee=10 xray= BasicNamedAndOptional Foxtrot: xray=10 yankee=test Foxtrot: xray=0 yankee=sam Quebec: xray=1 yankee=1 zulu=11 Quebec: xray=1 yankee=10 zulu=10 10 4 E: zero E: zero E: zero E: one System.Nullable`1[E]: zero System.Nullable`1[E]: zero System.Nullable`1[E]: zero System.Nullable`1[E]: one System.Nullable`1[E]: <null> System.Nullable`1[E]: <null> ELong: zero ELong: zero ELong: zero ELong: one System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: one System.Nullable`1[ELong]: <null> System.Nullable`1[ELong]: <null>"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnAttributes() { string source = @" using System; class MyAttribute : Attribute { public MyAttribute(int a = 1, int b = 2, int c = 3) { A = a; B = b; C = c; } public int X; public int A; public int B; public int C; } [MyAttribute(4, c:5, X=6)] class C { static void Main() { MyAttribute m1 = new MyAttribute(); Console.Write(m1.A); // 1 Console.Write(m1.B); // 2 Console.Write(m1.C); // 3 Console.Write(m1.X); // 0 MyAttribute m2 = new MyAttribute(c: 7); Console.Write(m2.A); // 1 Console.Write(m2.B); // 2 Console.Write(m2.C); // 7 Console.Write(m2.X); // 0 Type t = typeof(C); foreach (MyAttribute attr in t.GetCustomAttributes(false)) { Console.Write(attr.A); // 4 Console.Write(attr.B); // 2 Console.Write(attr.C); // 5 Console.Write(attr.X); // 6 } } }"; CompileAndVerify(source, expectedOutput: "123012704256"); } [Fact] public void TestNamedAndOptionalParamsOnIndexers() { string source = @" using System; class D { public int this[string s = ""four""] { get { return s.Length; } set { } } public int this[int x = 2, int y = 5] { get { return x + y; } set { } } public int this[string str = ""goo"", int i = 13] { get { Console.WriteLine(""D.this[str: '{0}', i: {1}].get"", str, i); return i;} set { Console.WriteLine(""D.this[str: '{0}', i: {1}].set"", str, i); } } } class C { int this[int x, int y] { get { return x + y; } set { } } static void Main() { C c = new C(); Console.WriteLine(c[y:10, x:10]); D d = new D(); Console.WriteLine(d[1]); Console.WriteLine(d[0,2]); Console.WriteLine(d[x:2]); Console.WriteLine(d[x:3, y:0]); Console.WriteLine(d[y:3, x:2]); Console.WriteLine(d[""abc""]); Console.WriteLine(d[s:""12345""]); d[i:1] = 0; d[str:""bar""] = 0; d[i:2, str:""baz""] = 0; d[str:""bah"", i:3] = 0; } }"; string expected = @"20 6 2 7 3 5 3 5 D.this[str: 'goo', i: 1].set D.this[str: 'bar', i: 13].set D.this[str: 'baz', i: 2].set D.this[str: 'bah', i: 3].set"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnPartialMethods() { string source = @" using System; partial class C { static partial void PartialMethod(int x); } partial class C { static partial void PartialMethod(int y) { Console.WriteLine(y); } static void Main() { // Declaring partial wins. PartialMethod(x:123); } }"; string expected = "123"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnPartialMethodsErrors() { string source = @" using System; partial class C { static partial void PartialMethod(int x); } partial class C { static partial void PartialMethod(int y) { Console.WriteLine(y); } static void Main() { // Implementing partial loses. PartialMethod(y:123); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,25): warning CS8826: Partial method declarations 'void C.PartialMethod(int x)' and 'void C.PartialMethod(int y)' have signature differences. // static partial void PartialMethod(int y) { Console.WriteLine(y); } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "PartialMethod").WithArguments("void C.PartialMethod(int x)", "void C.PartialMethod(int y)").WithLocation(9, 25), // (13,23): error CS1739: The best overload for 'PartialMethod' does not have a parameter named 'y' // PartialMethod(y:123); Diagnostic(ErrorCode.ERR_BadNamedArgument, "y").WithArguments("PartialMethod", "y").WithLocation(13, 23) ); } [Fact] public void TestNamedAndOptionalParametersUnsafe() { string source = @" using System; unsafe class C { static void M( int* x1 = default(int*), IntPtr x2 = default(IntPtr), UIntPtr x3 = default(UIntPtr), int x4 = default(int)) { } static void Main() { M(); } }"; // We make an improvement on the native compiler here; we generate default(UIntPtr) and // default(IntPtr) as "load zero, convert to type", rather than making a stack slot and calling // init on it. var c = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails); c.VerifyIL("C.Main", @"{ // Code size 13 (0xd) .maxstack 4 IL_0000: ldc.i4.0 IL_0001: conv.u IL_0002: ldc.i4.0 IL_0003: conv.i IL_0004: ldc.i4.0 IL_0005: conv.u IL_0006: ldc.i4.0 IL_0007: call ""void C.M(int*, System.IntPtr, System.UIntPtr, int)"" IL_000c: ret }"); } [WorkItem(528783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528783")] [Fact] public void TestNamedAndOptionalParametersArgumentName() { const string text = @" using System; namespace NS { class Test { static void M(sbyte sb = 0, string ss = null) {} static void Main() { M(/*<bind>*/ss/*</bind>*/: ""QC""); } } } "; var comp = CreateCompilation(text); var nodeAndModel = GetBindingNodeAndModel<IdentifierNameSyntax>(comp); var typeInfo = nodeAndModel.Item2.GetTypeInfo(nodeAndModel.Item1); // parameter name has no type Assert.Null(typeInfo.Type); var symInfo = nodeAndModel.Item2.GetSymbolInfo(nodeAndModel.Item1); Assert.NotNull(symInfo.Symbol); Assert.Equal(SymbolKind.Parameter, symInfo.Symbol.Kind); Assert.Equal("ss", symInfo.Symbol.Name); } [WorkItem(542418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542418")] [Fact] public void OptionalValueInvokesInstanceMethod() { var source = @"class C { object F() { return null; } void M1(object value = F()) { } object M2(object value = M2()) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,28): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 28), // (5,30): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 30)); } [Fact] public void OptionalValueInvokesStaticMethod() { var source = @"class C { static object F() { return null; } static void M1(object value = F()) { } static object M2(object value = M2()) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,35): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 35), // (5,37): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 37)); } [WorkItem(11638, "https://github.com/dotnet/roslyn/issues/11638")] [Fact] public void OptionalValueHasObjectInitializer() { var source = @"class C { static void Test(Vector3 vector = new Vector3() { X = 1f, Y = 1f, Z = 1f}) { } } public struct Vector3 { public float X; public float Y; public float Z; }"; CreateCompilation(source).VerifyDiagnostics( // (3,39): error CS1736: Default parameter value for 'vector' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new Vector3() { X = 1f, Y = 1f, Z = 1f}").WithArguments("vector").WithLocation(3, 39)); } [WorkItem(542411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542411")] [WorkItem(542365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542365")] [Fact] public void GenericOptionalParameters() { var source = @"class C { static void Goo<T>(T t = default(T)) {} }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void OptionalValueTypeFromReferencedAssembly() { // public struct S{} // public class C // { // public static void Goo(string s, S t = default(S)) {} // } string ilSource = @" // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 } // end of class S .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig static void Goo(string s, [opt] valuetype S t) cil managed { .param [2] = nullref // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::Goo } // end of class C "; var source = @" public class D { public static void Caller() { C.Goo(""""); } }"; CompileWithCustomILSource(source, ilSource); } [WorkItem(542867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542867")] [Fact] public void OptionalParameterDeclaredWithAttributes() { string source = @" using System.Runtime.InteropServices; public class Parent{ public int Goo([Optional]object i = null) { return 1; } public int Bar([DefaultParameterValue(1)]int i = 2) { return 1; } } class Test{ public static int Main(){ Parent p = new Parent(); return p.Goo(); } } "; CreateCompilation(source).VerifyDiagnostics( // (9,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public int Bar([DefaultParameterValue(1)]int i = 2) { Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(9, 21), // (9,54): error CS8017: The parameter has multiple distinct default values. // public int Bar([DefaultParameterValue(1)]int i = 2) { Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "2").WithLocation(9, 54), // (5,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public int Goo([Optional]object i = null) { Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(5, 21) ); } [WorkItem(10290, "DevDiv_Projects/Roslyn")] [Fact] public void OptionalParamOfTypeObject() { string source = @" public class Test { public static int M1(object p1 = null) { if (p1 == null) return 0; else return 1; } public static void Main() { System.Console.WriteLine(M1()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(543871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543871")] [Fact] public void RefParameterDeclaredWithOptionalAttribute() { // The native compiler produces "CS1501: No overload for method 'Goo' takes 0 arguments." // Roslyn produces a slightly more informative error message. string source = @" using System.Runtime.InteropServices; public class Parent { public static void Goo([Optional] ref int x) {} static void Main() { Goo(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Parent.Goo(ref int)' // Goo(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("x", "Parent.Goo(ref int)")); } [Fact, WorkItem(544491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544491")] public void EnumAsDefaultParameterValue() { string source = @" using System.Runtime.InteropServices; public enum MyEnum { one, two, three } public interface IOptionalRef { MyEnum MethodRef([In, Out, Optional, DefaultParameterValue(MyEnum.three)] ref MyEnum v); } "; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void DefaultParameterValueErrors() { string source = @" using System.Runtime.InteropServices; public enum I8 : sbyte { v = 1 } public enum U8 : byte { v = 1 } public enum I16 : short { v = 1 } public enum U16 : ushort { v = 1 } public enum I32 : int { v = 1 } public enum U32 : uint { v = 1 } public enum I64 : long { v = 1 } public enum U64 : ulong { v = 1 } public class C { } public delegate void D(); public interface I { } public struct S { } public static class ErrorCases { public static void M( // bool [Optional][DefaultParameterValue(0)] bool b1, [Optional][DefaultParameterValue(""hello"")] bool b2, // integral [Optional][DefaultParameterValue(12)] sbyte sb1, [Optional][DefaultParameterValue(""hello"")] byte by1, // char [Optional][DefaultParameterValue(""c"")] char ch1, // float [Optional][DefaultParameterValue(1.0)] float fl1, [Optional][DefaultParameterValue(1)] double dbl1, // enum [Optional][DefaultParameterValue(0)] I8 i8, [Optional][DefaultParameterValue(12)] U8 u8, [Optional][DefaultParameterValue(""hello"")] I16 i16, // string [Optional][DefaultParameterValue(5)] string str1, [Optional][DefaultParameterValue(new int[] { 12 })] string str2, // reference types [Optional][DefaultParameterValue(2)] C c1, [Optional][DefaultParameterValue(""hello"")] C c2, [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1, [DefaultParameterValue(null)] int[] arr2, [DefaultParameterValue(new int[] { 1, 2 })] object arr3, [DefaultParameterValue(typeof(object))] System.Type type1, [DefaultParameterValue(null)] System.Type type2, [DefaultParameterValue(typeof(object))] object type3, // user defined struct [DefaultParameterValue(null)] S userStruct1, [DefaultParameterValue(0)] S userStruct2, [DefaultParameterValue(""hel"")] S userStruct3, // null value to non-ref type [Optional][DefaultParameterValue(null)] bool b3, // integral [Optional][DefaultParameterValue(null)] int i2, // char [Optional][DefaultParameterValue(null)] char ch2, // float [Optional][DefaultParameterValue(null)] float fl2, // enum [Optional][DefaultParameterValue(null)] I8 i82 ) { } } "; // NOTE: anywhere dev10 reported CS1909, roslyn reports CS1910. CreateCompilation(source).VerifyDiagnostics( // (27,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(0)] bool b1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (28,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] bool b2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (31,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(12)] sbyte sb1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (32,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] byte by1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (35,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("c")] char ch1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (38,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(1.0)] float fl1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (42,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(0)] I8 i8, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (43,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(12)] U8 u8, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (44,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] I16 i16, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (47,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(5)] string str1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (48,20): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [Optional][DefaultParameterValue(new int[] { 12 })] string str2, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (51,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(2)] C c1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (52,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] C c2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (54,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // NOTE: Roslyn specifically allows this usage (illegal in dev10). //// (55,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'int[]', unless the default value is null //// [DefaultParameterValue(null)] int[] arr2, //Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("int[]"), // (56,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(new int[] { 1, 2 })] object arr3, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (58,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(typeof(object))] System.Type type1, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"), // NOTE: Roslyn specifically allows this usage (illegal in dev10). //// (59,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'System.Type', unless the default value is null //// [DefaultParameterValue(null)] System.Type type2, //Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("System.Type"), // (60,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(typeof(object))] object type3, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"), // (63,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue(null)] S userStruct1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (64,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue(0)] S userStruct2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (65,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue("hel")] S userStruct3, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (68,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] bool b3, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (71,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] int i2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (74,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] char ch2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (77,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] float fl2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (80,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] I8 i82 Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [WorkItem(544440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544440")] [ConditionalFact(typeof(DesktopOnly))] public void TestBug12768() { string sourceDefinitions = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public class C { public static void M1(object x = null) { Console.WriteLine(x ?? 1); } public static void M2([Optional] object x) { Console.WriteLine(x ?? 2); } public static void M3([MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 3); } public static void M4([MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 4); } public static void M5([IDispatchConstant] object x = null) { Console.WriteLine(x ?? 5); } public static void M6([IDispatchConstant] [Optional] object x) { Console.WriteLine(x ?? 6); } public static void M7([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 7); } public static void M8([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 8); } public static void M9([IUnknownConstant]object x = null) { Console.WriteLine(x ?? 9); } public static void M10([IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 10); } public static void M11([IUnknownConstant][MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 11); } public static void M12([IUnknownConstant][MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 12); } public static void M13([IUnknownConstant][IDispatchConstant] object x = null) { Console.WriteLine(x ?? 13); } public static void M14([IDispatchConstant][IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 14); } public static void M15([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 15); } public static void M16([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 16); } public static void M17([MarshalAs(UnmanagedType.Interface)][IDispatchConstant][Optional] object x) { Console.WriteLine(x ?? 17); } public static void M18([MarshalAs(UnmanagedType.Interface)][IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 18); } } "; string sourceCalls = @" internal class D { static void Main() { C.M1(); // null C.M2(); // Missing C.M3(); // null C.M4(); // null C.M5(); // null C.M6(); // DispatchWrapper C.M7(); // null C.M8(); // null C.M9(); // null C.M10(); // UnknownWrapper C.M11(); // null C.M12(); // null C.M13(); // null C.M14(); // UnknownWrapper C.M15(); // null C.M16(); // null C.M17(); // null C.M18(); // null } }"; string expected = @"1 System.Reflection.Missing 3 4 5 System.Runtime.InteropServices.DispatchWrapper 7 8 9 System.Runtime.InteropServices.UnknownWrapper 11 12 13 System.Runtime.InteropServices.UnknownWrapper 15 16 17 18"; // definitions in source: var verifier = CompileAndVerify(new[] { sourceDefinitions, sourceCalls }, expectedOutput: expected); // definitions in metadata: using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { CompileAndVerify(new[] { sourceCalls }, new[] { assembly.GetReference() }, expectedOutput: expected); } } [ConditionalFact(typeof(DesktopOnly))] public void IUnknownConstant_MissingType() { var source = @" using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { static void M0([Optional, MarshalAs(UnmanagedType.Interface)] object param) { } static void M1([Optional, IUnknownConstant] object param) { } static void M2([Optional, IDispatchConstant] object param) { } static void M3([Optional] object param) { } static void M() { M0(); M1(); M2(); M3(); } } "; CompileAndVerify(source).VerifyDiagnostics(); var comp = CreateCompilation(source); comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor); comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor); comp.MakeMemberMissing(WellKnownMember.System_Type__Missing); comp.VerifyDiagnostics( // (15,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.UnknownWrapper..ctor' // M1(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M1()").WithArguments("System.Runtime.InteropServices.UnknownWrapper", ".ctor").WithLocation(15, 9), // (16,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.DispatchWrapper..ctor' // M2(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M2()").WithArguments("System.Runtime.InteropServices.DispatchWrapper", ".ctor").WithLocation(16, 9), // (17,9): error CS0656: Missing compiler required member 'System.Type.Missing' // M3(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M3()").WithArguments("System.Type", "Missing").WithLocation(17, 9)); } [WorkItem(545329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545329")] [Fact()] public void ComOptionalRefParameter() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020813-0000-0000-c000-000000000046"")] interface ComClass { void M([Optional]ref object o); } class D : ComClass { public void M(ref object o) { } } class C { static void Main() { D d = new D(); ComClass c = d; c.M(); //fine d.M(); //CS1501 } } "; CreateCompilation(source).VerifyDiagnostics( // (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'D.M(ref object)' // d.M(); //CS1501 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "D.M(ref object)").WithLocation(25, 11)); } [WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")] [ClrOnlyFact] public void TestVbDecimalAndDateTimeDefaultParameters() { var vb = @" Imports System public Module VBModule Sub I(Optional ByVal x As System.Int32 = 456) Console.WriteLine(x) End Sub Sub NI(Optional ByVal x As System.Int32? = 457) Console.WriteLine(x) End Sub Sub OI(Optional ByVal x As Object = 458 ) Console.WriteLine(x) End Sub Sub DA(Optional ByVal x As DateTime = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub NDT(Optional ByVal x As DateTime? = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub ODT(Optional ByVal x As Object = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub Dec(Optional ByVal x as Decimal = 12.3D) Console.WriteLine(x.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub NDec(Optional ByVal x as Decimal? = 12.4D) Console.WriteLine(x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub ODec(Optional ByVal x as Object = 12.5D) Console.WriteLine(DirectCast(x, Decimal).ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub End Module "; var csharp = @" using System; public class D { static void Main() { // Ensure suites run in invariant culture across machines System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; // Possible in both C# and VB: VBModule.I(); VBModule.NI(); VBModule.Dec(); VBModule.NDec(); // Not possible in C#, possible in VB, but C# honours the parameter: VBModule.OI(); VBModule.ODec(); VBModule.DA(); VBModule.NDT(); VBModule.ODT(); } } "; string expected = @"456 457 12.3 12.4 458 12.5 True True True"; string il = @"{ // Code size 181 (0xb5) .maxstack 5 IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get"" IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get"" IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set"" IL_000f: ldc.i4 0x1c8 IL_0014: call ""void VBModule.I(int)"" IL_0019: ldc.i4 0x1c9 IL_001e: newobj ""int?..ctor(int)"" IL_0023: call ""void VBModule.NI(int?)"" IL_0028: ldc.i4.s 123 IL_002a: ldc.i4.0 IL_002b: ldc.i4.0 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0033: call ""void VBModule.Dec(decimal)"" IL_0038: ldc.i4.s 124 IL_003a: ldc.i4.0 IL_003b: ldc.i4.0 IL_003c: ldc.i4.0 IL_003d: ldc.i4.1 IL_003e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0043: newobj ""decimal?..ctor(decimal)"" IL_0048: call ""void VBModule.NDec(decimal?)"" IL_004d: ldc.i4 0x1ca IL_0052: box ""int"" IL_0057: call ""void VBModule.OI(object)"" IL_005c: ldc.i4.s 125 IL_005e: ldc.i4.0 IL_005f: ldc.i4.0 IL_0060: ldc.i4.0 IL_0061: ldc.i4.1 IL_0062: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0067: box ""decimal"" IL_006c: call ""void VBModule.ODec(object)"" IL_0071: ldc.i8 0x8c8fc181490c000 IL_007a: newobj ""System.DateTime..ctor(long)"" IL_007f: call ""void VBModule.DA(System.DateTime)"" IL_0084: ldc.i8 0x8c8fc181490c000 IL_008d: newobj ""System.DateTime..ctor(long)"" IL_0092: newobj ""System.DateTime?..ctor(System.DateTime)"" IL_0097: call ""void VBModule.NDT(System.DateTime?)"" IL_009c: ldc.i8 0x8c8fc181490c000 IL_00a5: newobj ""System.DateTime..ctor(long)"" IL_00aa: box ""System.DateTime"" IL_00af: call ""void VBModule.ODT(object)"" IL_00b4: ret }"; var vbCompilation = CreateVisualBasicCompilation("VB", vb, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbCompilation.VerifyDiagnostics(); var csharpCompilation = CreateCSharpCompilation("CS", csharp, compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new[] { vbCompilation }); var verifier = CompileAndVerify(csharpCompilation, expectedOutput: expected); verifier.VerifyIL("D.Main", il); } [WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")] [Fact] public void TestCSharpDecimalAndDateTimeDefaultParameters() { var library = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public enum E { one, two, three } public class C { public void Goo( [Optional][DateTimeConstant(100000)]DateTime dateTime, decimal dec = 12345678901234567890m, int? x = 0, int? q = null, short y = 10, int z = default(int), S? s = null) //S? s2 = default(S)) { if (dateTime == new DateTime(100000)) { Console.WriteLine(""DatesMatch""); } else { Console.WriteLine(""Dates dont match!!""); } Write(dec); Write(x); Write(q); Write(y); Write(z); Write(s); //Write(s2); } public void Bar(S? s1, S? s2, S? s3) { } public void Baz(E? e1 = E.one, long? x = 0) { if (e1.HasValue) { Console.WriteLine(e1); } else { Console.WriteLine(""null""); } Console.WriteLine(x); } public void Write(object o) { if (o == null) { Console.WriteLine(""null""); } else { Console.WriteLine(o); } } } public struct S { } "; var main = @" using System; public class D { static void Main() { // Ensure suites run in invariant culture across machines System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; C c = new C(); c.Goo(); c.Baz(); } } "; var libComp = CreateCompilation(library, options: TestOptions.ReleaseDll, assemblyName: "Library"); libComp.VerifyDiagnostics(); var exeComp = CreateCompilation(main, new[] { new CSharpCompilationReference(libComp) }, options: TestOptions.ReleaseExe, assemblyName: "Main"); var verifier = CompileAndVerify(exeComp, expectedOutput: @"DatesMatch 12345678901234567890 0 null 10 0 null one 0"); verifier.VerifyIL("D.Main", @"{ // Code size 97 (0x61) .maxstack 9 .locals init (int? V_0, S? V_1) IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get"" IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get"" IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set"" IL_000f: newobj ""C..ctor()"" IL_0014: dup IL_0015: ldc.i4 0x186a0 IL_001a: conv.i8 IL_001b: newobj ""System.DateTime..ctor(long)"" IL_0020: ldc.i8 0xab54a98ceb1f0ad2 IL_0029: newobj ""decimal..ctor(ulong)"" IL_002e: ldc.i4.0 IL_002f: newobj ""int?..ctor(int)"" IL_0034: ldloca.s V_0 IL_0036: initobj ""int?"" IL_003c: ldloc.0 IL_003d: ldc.i4.s 10 IL_003f: ldc.i4.0 IL_0040: ldloca.s V_1 IL_0042: initobj ""S?"" IL_0048: ldloc.1 IL_0049: callvirt ""void C.Goo(System.DateTime, decimal, int?, int?, short, int, S?)"" IL_004e: ldc.i4.0 IL_004f: newobj ""E?..ctor(E)"" IL_0054: ldc.i4.0 IL_0055: conv.i8 IL_0056: newobj ""long?..ctor(long)"" IL_005b: callvirt ""void C.Baz(E?, long?)"" IL_0060: ret }"); } [Fact] public void OmittedComOutParameter() { // We allow omitting optional ref arguments but not optional out arguments. var source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""989FE455-5A6D-4D05-A349-1A221DA05FDA"")] interface I { void M([Optional]out object o); } class P { static void Q(I i) { i.M(); } } "; // Note that the native compiler gives a slightly less informative error message here. var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,26): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'I.M(out object)' // static void Q(I i) { i.M(); } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "I.M(out object)") ); } [Fact] public void OmittedComRefParameter() { var source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""A8FAF53B-F502-4465-9429-CAB2A19B47BE"")] interface ICom { void M(out int w, int x, [Optional]ref object o, int z = 0); } class Com : ICom { public void M(out int w, int x, ref object o, int z) { w = 123; Console.WriteLine(x); if (o != null) { Console.WriteLine(o.GetType()); } else { Console.WriteLine(""null""); } Console.WriteLine(z); } static void Main() { ICom c = new Com(); int q; c.M(w: out q, z: 10, x: 100); Console.WriteLine(q); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" 100 System.Reflection.Missing 10 123"); verifier.VerifyIL("Com.Main", @" { // Code size 31 (0x1f) .maxstack 5 .locals init (int V_0, //q object V_1) IL_0000: newobj ""Com..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 100 IL_0009: ldsfld ""object System.Type.Missing"" IL_000e: stloc.1 IL_000f: ldloca.s V_1 IL_0011: ldc.i4.s 10 IL_0013: callvirt ""void ICom.M(out int, int, ref object, int)"" IL_0018: ldloc.0 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ret }"); } [Fact] public void ArrayElementComRefParameter() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")] interface IA { void M(ref int i); } class A : IA { void IA.M(ref int i) { i += 2; } } class B { static void M(IA a) { a.M(F()[0]); } static void MByRef(IA a) { a.M(ref F()[0]); } static int[] i = { 0 }; static int[] F() { Console.WriteLine(""F()""); return i; } static void Main() { IA a = new A(); M(a); ReportAndReset(); MByRef(a); ReportAndReset(); } static void ReportAndReset() { Console.WriteLine(""{0}"", i[0]); i = new[] { 0 }; } }"; var verifier = CompileAndVerify(source, expectedOutput: @"F() 0 F() 2"); verifier.VerifyIL("B.M(IA)", @"{ // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""int[] B.F()"" IL_0006: ldc.i4.0 IL_0007: ldelem.i4 IL_0008: stloc.0 IL_0009: ldloca.s V_0 IL_000b: callvirt ""void IA.M(ref int)"" IL_0010: ret }"); verifier.VerifyIL("B.MByRef(IA)", @"{ // Code size 18 (0x12) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int[] B.F()"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: callvirt ""void IA.M(ref int)"" IL_0011: ret }"); } [Fact] public void ArrayElementComRefParametersReordered() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")] interface IA { void M(ref int x, ref int y); } class A : IA { void IA.M(ref int x, ref int y) { x += 2; y += 3; } } class B { static void M(IA a) { a.M(y: ref F2()[0], x: ref F1()[0]); } static int[] i1 = { 0 }; static int[] i2 = { 0 }; static int[] F1() { Console.WriteLine(""F1()""); return i1; } static int[] F2() { Console.WriteLine(""F2()""); return i2; } static void Main() { IA a = new A(); M(a); Console.WriteLine(""{0}, {1}"", i1[0], i2[0]); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"F2() F1() 2, 3 "); verifier.VerifyIL("B.M(IA)", @"{ // Code size 31 (0x1f) .maxstack 3 .locals init (int& V_0) IL_0000: ldarg.0 IL_0001: call ""int[] B.F2()"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: stloc.0 IL_000d: call ""int[] B.F1()"" IL_0012: ldc.i4.0 IL_0013: ldelema ""int"" IL_0018: ldloc.0 IL_0019: callvirt ""void IA.M(ref int, ref int)"" IL_001e: ret }"); } [Fact] [WorkItem(546713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546713")] public void Test16631() { var source = @" public abstract class B { protected abstract void E<T>(); } public class D : B { void M() { // There are two possible methods to choose here. The static method // is better because it is declared in a more derived class; the // virtual method is better because it has exactly the right number // of parameters. In this case, the static method wins. The virtual // method is to be treated as though it was a method of the base class, // and therefore automatically loses. (The bug we are regressing here // is that Roslyn did not correctly identify the originally-defining // type B when the method E was generic. The original repro scenario in // bug 16631 was much more complicated than this, but it boiled down to // overload resolution choosing the wrong method.) E<int>(); } protected override void E<T>() { System.Console.WriteLine(1); } static void E<T>(int x = 0xBEEF) { System.Console.WriteLine(2); } static void Main() { (new D()).M(); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyIL("D.M()", @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldc.i4 0xbeef IL_0005: call ""void D.E<int>(int)"" IL_000a: ret }"); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_PrimitiveStruct() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(int p) { } public void M1(int p = 0) { } // default of type public void M2(int p = 1) { } // not default of type public void M3([Optional]int p) { } // no default specified (would be illegal) public void M4([DefaultParameterValue(0)]int p) { } // default of type, not optional public void M5([DefaultParameterValue(1)]int p) { } // not default of type, not optional public void M6([Optional][DefaultParameterValue(0)]int p) { } // default of type, optional public void M7([Optional][DefaultParameterValue(1)]int p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal(0, parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0), parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal(1, parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.True(parameters[4].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create(0), parameters[4].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length); Assert.False(parameters[5].IsOptional); Assert.False(parameters[5].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue); Assert.True(parameters[5].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create(1), parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[5].GetAttributes().Length); Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(0, parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal(1, parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1), parameters[7].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_UserDefinedStruct() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(S p) { } public void M1(S p = default(S)) { } public void M2([Optional]S p) { } // no default specified (would be illegal) } public struct S { public int x; } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(3, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.False(parameters[2].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length); }; // TODO: RefEmit doesn't emit the default value of M1's parameter. CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_String() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(string p) { } public void M1(string p = null) { } public void M2(string p = ""A"") { } public void M3([Optional]string p) { } // no default specified (would be illegal) public void M4([DefaultParameterValue(null)]string p) { } public void M5([Optional][DefaultParameterValue(null)]string p) { } public void M6([DefaultParameterValue(""A"")]string p) { } public void M7([Optional][DefaultParameterValue(""A"")]string p) { } } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal("A", parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create("A"), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.True(parameters[4].HasMetadataConstantValue); Assert.Equal(ConstantValue.Null, parameters[4].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length); Assert.True(parameters[5].IsOptional); Assert.True(parameters[5].HasExplicitDefaultValue); Assert.Null(parameters[5].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); Assert.False(parameters[6].IsOptional); Assert.False(parameters[6].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[6].ExplicitDefaultValue); Assert.True(parameters[6].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create("A"), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[6].GetAttributes().Length); Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal("A", parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create("A"), parameters[7].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_Decimal() { var source = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C { public void M0(decimal p) { } public void M1(decimal p = 0) { } // default of type public void M2(decimal p = 1) { } // not default of type public void M3([Optional]decimal p) { } // no default specified (would be illegal) public void M4([DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, not optional public void M5([DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, not optional public void M6([Optional][DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, optional public void M7([Optional][DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal(0M, parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0M), parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal(1M, parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1M), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.False(parameters[4].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(0M) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[4].GetAttributes().Length); // DecimalConstantAttribute Assert.False(parameters[5].IsOptional); Assert.False(parameters[5].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue); Assert.False(parameters[5].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(1M) : null, parameters[5].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[5].GetAttributes().Length); // DecimalConstantAttribute Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(0M, parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0M), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal(1M, parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1M), parameters[7].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_DateTime() { var source = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C { public void M0(DateTime p) { } public void M1(DateTime p = default(DateTime)) { } public void M2([Optional]DateTime p) { } // no default specified (would be illegal) public void M3([DateTimeConstant(0)]DateTime p) { } // default of type, not optional public void M4([DateTimeConstant(1)]DateTime p) { } // not default of type, not optional public void M5([Optional][DateTimeConstant(0)]DateTime p) { } // default of type, optional public void M6([Optional][DateTimeConstant(1)]DateTime p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(7, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); // As in dev11, [DateTimeConstant] is not emitted in this case. Assert.True(parameters[2].IsOptional); Assert.False(parameters[2].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length); Assert.False(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.False(parameters[3].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(0)) : null, parameters[3].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[3].GetAttributes().Length); // DateTimeConstant Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.False(parameters[4].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(1)) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[4].GetAttributes().Length); // DateTimeConstant Assert.True(parameters[5].IsOptional); Assert.True(parameters[5].HasExplicitDefaultValue); Assert.Equal(new DateTime(0), parameters[5].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(new DateTime(0)), parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(new DateTime(1), parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(new DateTime(1)), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant }; // TODO: Guess - RefEmit doesn't like DateTime constants. CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] public void InvalidConversionForDefaultArgument_InIL() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method P::.ctor .method public hidebysig instance int32 M1([opt] int32 s) cil managed { .param [1] = ""abc"" // Code size 2 (0x2) .maxstack 8 IL_0000: ldarg.1 IL_0001: ret } // end of method P::M1 } // end of class P "; var csharp = @" class C { public static void Main() { P p = new P(); System.Console.Write(p.M1()); } } "; var comp = CreateCompilationWithIL(csharp, il, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,31): error CS0029: Cannot implicitly convert type 'string' to 'int' // System.Console.Write(p.M1()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 31)); } [Fact] public void DefaultArgument_LoopInUsage() { var csharp = @" class C { static object F(object param = F()) => param; // 1 } "; var comp = CreateCompilation(csharp); comp.VerifyDiagnostics( // (4,36): error CS1736: Default parameter value for 'param' must be a compile-time constant // static object F(object param = F()) => param; // 1 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("param").WithLocation(4, 36)); var method = comp.GetMember<MethodSymbol>("C.F"); var param = method.Parameters.Single(); Assert.Equal(ConstantValue.Bad, param.ExplicitDefaultConstantValue); } [Fact] public void DefaultValue_Boxing() { var csharp = @" class C { void M1(object obj = 1) // 1 { } C(object obj = System.DayOfWeek.Monday) // 2 { } } "; var comp = CreateCompilation(csharp); comp.VerifyDiagnostics( // (4,20): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // void M1(object obj = 1) // 1 Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(4, 20), // (8,14): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // C(object obj = System.DayOfWeek.Monday) // 2 Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(8, 14)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NamedAndOptionalTests : CompilingTestBase { [Fact] public void Test13984() { string source = @" using System; class Program { static void Main() { } static void M(DateTime da = new DateTime(2012, 6, 22), decimal d = new decimal(5), int i = new int()) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,33): error CS1736: Default parameter value for 'da' must be a compile-time constant // static void M(DateTime da = new DateTime(2012, 6, 22), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new DateTime(2012, 6, 22)").WithArguments("da"), // (7,31): error CS1736: Default parameter value for 'd' must be a compile-time constant // decimal d = new decimal(5), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new decimal(5)").WithArguments("d")); } [Fact] public void Test13861() { // * There are two decimal constant attribute constructors; we should honour both of them. // * Using named arguments to re-order the arguments must not change the value of the constant. string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { public static void Goo1([Optional][DecimalConstant(0, 0, low: (uint)100, mid: (uint)0, hi: (uint)0)] decimal i) { System.Console.Write(i); } public static void Goo2([Optional][DecimalConstant(0, 0, 0, 0, 200)] decimal i) { System.Console.Write(i); } static void Main(string[] args) { Goo1(); Goo2(); } }"; string expected = "100200"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsInCtors() { string source = @" class Alpha { public Alpha(int x = 123) { } } class Bravo : Alpha { // See bug 7846. // This should be legal; the generated ctor for Bravo should call base(123) } class Charlie : Alpha { public Charlie() : base() {} // This should be legal; should call base(123) } class Delta : Alpha { public Delta() {} // This should be legal; should call base(123) } abstract class Echo { protected Echo(int x = 123) {} } abstract class Foxtrot : Echo { } abstract class Hotel : Echo { protected Hotel() {} } abstract class Golf : Echo { protected Golf() : base() {} } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestNamedAndOptionalParamsErrors() { string source = @" class Base { public virtual void Goo(int reqParam1, int optParam1 = 0, int optParam2 = default(int), int optParam3 = new int(), string optParam4 = null, double optParam5 = 128L) { } } class Middle : Base { //override and change the parameters names public override void Goo(int reqChParam1, int optChParam1 = 0, int optChParam2 = default(int), int optChParam3 = new int(), string optChParam4 = null, double optChParam5 = 128L) { } } class C : Middle { public void Q(params int[] x) {} public void M() { var c = new C(); // calling child class parameters with base names // error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3' c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111); // error CS1738: Named argument specifications must appear after all fixed arguments have been specified c.Goo(optArg1: 3333, 11111); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (37,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3' // c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111); Diagnostic(ErrorCode.ERR_BadNamedArgument, "optParam3").WithArguments("Goo", "optParam3").WithLocation(37, 15), // (39,30): 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.Goo(optArg1: 3333, 11111); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "11111").WithArguments("7.2").WithLocation(39, 30), // (39,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optArg1' // c.Goo(optArg1: 3333, 11111); Diagnostic(ErrorCode.ERR_BadNamedArgument, "optArg1").WithArguments("Goo", "optArg1").WithLocation(39, 15) ); } [Fact] public void TestNamedAndOptionalParamsErrors2() { string source = @" class C { //error CS1736 public void M(string s = new string('c',5)) {} }"; CreateCompilation(source).VerifyDiagnostics( // (5,30): error CS1736: Default parameter value for 's' must be a compile-time constant // public void M(string s = new string('c',5)) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new string('c',5)").WithArguments("s").WithLocation(5, 30)); } [Fact] public void TestNamedAndOptionalParamsErrors3() { // Here we cannot report that "no overload of M takes two arguments" because of course // M(1, 2) is legal. We cannot report that any argument does not correspond to a formal; // all of them do. We cannot report that named arguments precede positional arguments. // We cannot report that any argument is not convertible to its corresponding formal; // all of them are convertible. The only error we can report here is that a formal // parameter has no corresponding argument. string source = @" class C { // CS7036 (ERR_NoCorrespondingArgument) delegate void F(int fx, int fg, int fz = 123); C(int cx, int cy, int cz = 123) {} public static void M(int mx, int my, int mz = 123) { F f = null; f(0, fz : 456); M(0, mz : 456); new C(0, cz : 456); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'fg' of 'C.F' // f(0, fz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "f").WithArguments("fg", "C.F").WithLocation(10, 9), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'my' of 'C.M(int, int, int)' // M(0, mz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("my", "C.M(int, int, int)").WithLocation(11, 9), // (12,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'cy' of 'C.C(int, int, int)' // new C(0, cz : 456); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("cy", "C.C(int, int, int)").WithLocation(12, 13)); } [Fact] public void TestNamedAndOptionalParamsCrazy() { // This was never supposed to work and the spec does not require it, but // nevertheless, the native compiler allows this: const string source = @" class C { static void C(int q = 10, params int[] x) {} static int X() { return 123; } static int Q() { return 345; } static void M() { C(x:X(), q:Q()); } }"; // and so Roslyn does too. It seems likely that someone has taken a dependency // on the bad pattern. CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type // static void C(int q = 10, params int[] x) {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15)); } [Fact] public void TestNamedAndOptionalParamsCrazyError() { // Fortunately, however, this is still illegal: const string source = @" class C { static void C(int q = 10, params int[] x) {} static void M() { C(1, 2, 3, x:4); } }"; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type // static void C(int q = 10, params int[] x) {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15), // (7,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // C(1, 2, 3, x:4); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(7, 16)); } [Fact] public void TestNamedAndOptionalParamsBasic() { string source = @" using System; public enum E { zero, one, two, three } public enum ELong : long { zero, one, two, three } public class EnumDefaultValues { public static void Run() { var x = new EnumDefaultValues(); x.M(); } void M( E e1 = 0, E e2 = default(E), E e3 = E.zero, E e4 = E.one, E? ne1 = 0, E? ne2 = default(E), E? ne3 = E.zero, E? ne4 = E.one, E? ne5 = null, E? ne6 = default(E?), ELong el1 = 0, ELong el2 = default(ELong), ELong el3 = ELong.zero, ELong el4 = ELong.one, ELong? nel1 = 0, ELong? nel2 = default(ELong), ELong? nel3 = ELong.zero, ELong? nel4 = ELong.one, ELong? nel5 = null, ELong? nel6 = default(ELong?) ) { Show(e1); Show(e2); Show(e3); Show(e4); Show(ne1); Show(ne2); Show(ne3); Show(ne4); Show(ne5); Show(ne6); Show(el1); Show(el2); Show(el3); Show(el4); Show(nel1); Show(nel2); Show(nel3); Show(nel4); Show(nel5); Show(nel6); } static void Show<T>(T t) { object o = t; Console.WriteLine(""{0}: {1}"", typeof(T), o != null ? o : ""<null>""); } } struct Sierra { public Alpha alpha; public Bravo bravo; public int i; public Sierra(Alpha alpha, Bravo bravo, int i) { this.alpha = alpha; this.bravo = bravo; this.i = i; } } class Alpha { public virtual int Mike(int xray) { return xray; } } class Bravo : Alpha { public override int Mike(int yankee) { return yankee; } } class Charlie : Bravo { void Foxtrot( int xray = 10, string yankee = ""sam"") { Console.WriteLine(""Foxtrot: xray={0} yankee={1}"", xray, yankee); } void Quebec( int xray, int yankee = 10, int zulu = 11) { Console.WriteLine(""Quebec: xray={0} yankee={1} zulu={2}"", xray, yankee, zulu); } void OutRef( out int xray, ref int yankee) { xray = 0; yankee = 0; } void ParamArray(params int[] xray) { Console.WriteLine(""ParamArray: xray={0}"", string.Join<int>("","", xray)); } void ParamArray2( int yankee = 10, params int[] xray) { Console.WriteLine(""ParamArray2: yankee={0} xray={1}"", yankee, string.Join<int>("","", xray)); } void Zeros( int xray = 0, int? yankee = 0, int? zulu = null, Charlie charlie = null) { Console.WriteLine(""Zeros: xray={0} yankee={1} zulu={2} charlie={3}"", xray, yankee == null ? ""null"" : yankee.ToString(), zulu == null ? ""null"" : zulu.ToString(), charlie == null ? ""null"" : charlie.ToString() ); } void OtherDefaults( string str = default(string), Alpha alpha = default(Alpha), Bravo bravo = default(Bravo), int i = default(int), Sierra sierra = default(Sierra)) { Console.WriteLine(""OtherDefaults: str={0} alpha={1} bravo={2} i={3} sierra={4}"", str == null ? ""null"" : str, alpha == null ? ""null"" : alpha.ToString(), bravo == null ? ""null"" : bravo.ToString(), i, sierra.alpha == null && sierra.bravo == null && sierra.i == 0 ? ""default(Sierra)"" : sierra.ToString()); } int Bar() { Console.WriteLine(""Bar""); return 96; } string Baz() { Console.WriteLine(""Baz""); return ""Baz""; } void BasicOptionalTests() { Console.WriteLine(""BasicOptional""); Foxtrot(0); Foxtrot(); ParamArray(1, 2, 3); Zeros(); OtherDefaults(); } void BasicNamedTests() { Console.WriteLine(""BasicNamed""); // Basic named test. Foxtrot(yankee: ""test"", xray: 1); Foxtrot(xray: 1, yankee: ""test""); // Test to see which execution comes first. Foxtrot(yankee: Baz(), xray: Bar()); int y = 100; int x = 100; OutRef(yankee: ref y, xray: out x); Console.WriteLine(x); Console.WriteLine(y); Charlie c = new Charlie(); ParamArray(xray: 1); ParamArray(xray: new int[] { 1, 2, 3 }); ParamArray2(xray: 1); ParamArray2(xray: new int[] { 1, 2, 3 }); ParamArray2(xray: 1, yankee: 20); ParamArray2(xray: new int[] { 1, 2, 3 }, yankee: 20); ParamArray2(); } void BasicNamedAndOptionalTests() { Console.WriteLine(""BasicNamedAndOptional""); Foxtrot(yankee: ""test""); Foxtrot(xray: 0); Quebec(1, yankee: 1); Quebec(1, zulu: 10); } void OverrideTest() { Console.WriteLine(Mike(yankee: 10)); } void TypeParamTest<T>() where T : Bravo, new() { T t = new T(); Console.WriteLine(t.Mike(yankee: 4)); } static void Main() { Charlie c = new Charlie(); c.BasicOptionalTests(); c.BasicNamedTests(); c.BasicNamedAndOptionalTests(); c.OverrideTest(); c.TypeParamTest<Bravo>(); EnumDefaultValues.Run(); } } "; string expected = @"BasicOptional Foxtrot: xray=0 yankee=sam Foxtrot: xray=10 yankee=sam ParamArray: xray=1,2,3 Zeros: xray=0 yankee=0 zulu=null charlie=null OtherDefaults: str=null alpha=null bravo=null i=0 sierra=default(Sierra) BasicNamed Foxtrot: xray=1 yankee=test Foxtrot: xray=1 yankee=test Baz Bar Foxtrot: xray=96 yankee=Baz 0 0 ParamArray: xray=1 ParamArray: xray=1,2,3 ParamArray2: yankee=10 xray=1 ParamArray2: yankee=10 xray=1,2,3 ParamArray2: yankee=20 xray=1 ParamArray2: yankee=20 xray=1,2,3 ParamArray2: yankee=10 xray= BasicNamedAndOptional Foxtrot: xray=10 yankee=test Foxtrot: xray=0 yankee=sam Quebec: xray=1 yankee=1 zulu=11 Quebec: xray=1 yankee=10 zulu=10 10 4 E: zero E: zero E: zero E: one System.Nullable`1[E]: zero System.Nullable`1[E]: zero System.Nullable`1[E]: zero System.Nullable`1[E]: one System.Nullable`1[E]: <null> System.Nullable`1[E]: <null> ELong: zero ELong: zero ELong: zero ELong: one System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: zero System.Nullable`1[ELong]: one System.Nullable`1[ELong]: <null> System.Nullable`1[ELong]: <null>"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnAttributes() { string source = @" using System; class MyAttribute : Attribute { public MyAttribute(int a = 1, int b = 2, int c = 3) { A = a; B = b; C = c; } public int X; public int A; public int B; public int C; } [MyAttribute(4, c:5, X=6)] class C { static void Main() { MyAttribute m1 = new MyAttribute(); Console.Write(m1.A); // 1 Console.Write(m1.B); // 2 Console.Write(m1.C); // 3 Console.Write(m1.X); // 0 MyAttribute m2 = new MyAttribute(c: 7); Console.Write(m2.A); // 1 Console.Write(m2.B); // 2 Console.Write(m2.C); // 7 Console.Write(m2.X); // 0 Type t = typeof(C); foreach (MyAttribute attr in t.GetCustomAttributes(false)) { Console.Write(attr.A); // 4 Console.Write(attr.B); // 2 Console.Write(attr.C); // 5 Console.Write(attr.X); // 6 } } }"; CompileAndVerify(source, expectedOutput: "123012704256"); } [Fact] public void TestNamedAndOptionalParamsOnIndexers() { string source = @" using System; class D { public int this[string s = ""four""] { get { return s.Length; } set { } } public int this[int x = 2, int y = 5] { get { return x + y; } set { } } public int this[string str = ""goo"", int i = 13] { get { Console.WriteLine(""D.this[str: '{0}', i: {1}].get"", str, i); return i;} set { Console.WriteLine(""D.this[str: '{0}', i: {1}].set"", str, i); } } } class C { int this[int x, int y] { get { return x + y; } set { } } static void Main() { C c = new C(); Console.WriteLine(c[y:10, x:10]); D d = new D(); Console.WriteLine(d[1]); Console.WriteLine(d[0,2]); Console.WriteLine(d[x:2]); Console.WriteLine(d[x:3, y:0]); Console.WriteLine(d[y:3, x:2]); Console.WriteLine(d[""abc""]); Console.WriteLine(d[s:""12345""]); d[i:1] = 0; d[str:""bar""] = 0; d[i:2, str:""baz""] = 0; d[str:""bah"", i:3] = 0; } }"; string expected = @"20 6 2 7 3 5 3 5 D.this[str: 'goo', i: 1].set D.this[str: 'bar', i: 13].set D.this[str: 'baz', i: 2].set D.this[str: 'bah', i: 3].set"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnPartialMethods() { string source = @" using System; partial class C { static partial void PartialMethod(int x); } partial class C { static partial void PartialMethod(int y) { Console.WriteLine(y); } static void Main() { // Declaring partial wins. PartialMethod(x:123); } }"; string expected = "123"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TestNamedAndOptionalParamsOnPartialMethodsErrors() { string source = @" using System; partial class C { static partial void PartialMethod(int x); } partial class C { static partial void PartialMethod(int y) { Console.WriteLine(y); } static void Main() { // Implementing partial loses. PartialMethod(y:123); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,25): warning CS8826: Partial method declarations 'void C.PartialMethod(int x)' and 'void C.PartialMethod(int y)' have signature differences. // static partial void PartialMethod(int y) { Console.WriteLine(y); } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "PartialMethod").WithArguments("void C.PartialMethod(int x)", "void C.PartialMethod(int y)").WithLocation(9, 25), // (13,23): error CS1739: The best overload for 'PartialMethod' does not have a parameter named 'y' // PartialMethod(y:123); Diagnostic(ErrorCode.ERR_BadNamedArgument, "y").WithArguments("PartialMethod", "y").WithLocation(13, 23) ); } [Fact] public void TestNamedAndOptionalParametersUnsafe() { string source = @" using System; unsafe class C { static void M( int* x1 = default(int*), IntPtr x2 = default(IntPtr), UIntPtr x3 = default(UIntPtr), int x4 = default(int)) { } static void Main() { M(); } }"; // We make an improvement on the native compiler here; we generate default(UIntPtr) and // default(IntPtr) as "load zero, convert to type", rather than making a stack slot and calling // init on it. var c = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails); c.VerifyIL("C.Main", @"{ // Code size 13 (0xd) .maxstack 4 IL_0000: ldc.i4.0 IL_0001: conv.u IL_0002: ldc.i4.0 IL_0003: conv.i IL_0004: ldc.i4.0 IL_0005: conv.u IL_0006: ldc.i4.0 IL_0007: call ""void C.M(int*, System.IntPtr, System.UIntPtr, int)"" IL_000c: ret }"); } [WorkItem(528783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528783")] [Fact] public void TestNamedAndOptionalParametersArgumentName() { const string text = @" using System; namespace NS { class Test { static void M(sbyte sb = 0, string ss = null) {} static void Main() { M(/*<bind>*/ss/*</bind>*/: ""QC""); } } } "; var comp = CreateCompilation(text); var nodeAndModel = GetBindingNodeAndModel<IdentifierNameSyntax>(comp); var typeInfo = nodeAndModel.Item2.GetTypeInfo(nodeAndModel.Item1); // parameter name has no type Assert.Null(typeInfo.Type); var symInfo = nodeAndModel.Item2.GetSymbolInfo(nodeAndModel.Item1); Assert.NotNull(symInfo.Symbol); Assert.Equal(SymbolKind.Parameter, symInfo.Symbol.Kind); Assert.Equal("ss", symInfo.Symbol.Name); } [WorkItem(542418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542418")] [Fact] public void OptionalValueInvokesInstanceMethod() { var source = @"class C { object F() { return null; } void M1(object value = F()) { } object M2(object value = M2()) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,28): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 28), // (5,30): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 30)); } [Fact] public void OptionalValueInvokesStaticMethod() { var source = @"class C { static object F() { return null; } static void M1(object value = F()) { } static object M2(object value = M2()) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,35): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 35), // (5,37): error CS1736: Default parameter value for 'value' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 37)); } [WorkItem(11638, "https://github.com/dotnet/roslyn/issues/11638")] [Fact] public void OptionalValueHasObjectInitializer() { var source = @"class C { static void Test(Vector3 vector = new Vector3() { X = 1f, Y = 1f, Z = 1f}) { } } public struct Vector3 { public float X; public float Y; public float Z; }"; CreateCompilation(source).VerifyDiagnostics( // (3,39): error CS1736: Default parameter value for 'vector' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new Vector3() { X = 1f, Y = 1f, Z = 1f}").WithArguments("vector").WithLocation(3, 39)); } [WorkItem(542411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542411")] [WorkItem(542365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542365")] [Fact] public void GenericOptionalParameters() { var source = @"class C { static void Goo<T>(T t = default(T)) {} }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void OptionalValueTypeFromReferencedAssembly() { // public struct S{} // public class C // { // public static void Goo(string s, S t = default(S)) {} // } string ilSource = @" // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 } // end of class S .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig static void Goo(string s, [opt] valuetype S t) cil managed { .param [2] = nullref // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::Goo } // end of class C "; var source = @" public class D { public static void Caller() { C.Goo(""""); } }"; CompileWithCustomILSource(source, ilSource); } [WorkItem(542867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542867")] [Fact] public void OptionalParameterDeclaredWithAttributes() { string source = @" using System.Runtime.InteropServices; public class Parent{ public int Goo([Optional]object i = null) { return 1; } public int Bar([DefaultParameterValue(1)]int i = 2) { return 1; } } class Test{ public static int Main(){ Parent p = new Parent(); return p.Goo(); } } "; CreateCompilation(source).VerifyDiagnostics( // (9,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public int Bar([DefaultParameterValue(1)]int i = 2) { Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(9, 21), // (9,54): error CS8017: The parameter has multiple distinct default values. // public int Bar([DefaultParameterValue(1)]int i = 2) { Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "2").WithLocation(9, 54), // (5,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public int Goo([Optional]object i = null) { Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(5, 21) ); } [WorkItem(10290, "DevDiv_Projects/Roslyn")] [Fact] public void OptionalParamOfTypeObject() { string source = @" public class Test { public static int M1(object p1 = null) { if (p1 == null) return 0; else return 1; } public static void Main() { System.Console.WriteLine(M1()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(543871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543871")] [Fact] public void RefParameterDeclaredWithOptionalAttribute() { // The native compiler produces "CS1501: No overload for method 'Goo' takes 0 arguments." // Roslyn produces a slightly more informative error message. string source = @" using System.Runtime.InteropServices; public class Parent { public static void Goo([Optional] ref int x) {} static void Main() { Goo(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Parent.Goo(ref int)' // Goo(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("x", "Parent.Goo(ref int)")); } [Fact, WorkItem(544491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544491")] public void EnumAsDefaultParameterValue() { string source = @" using System.Runtime.InteropServices; public enum MyEnum { one, two, three } public interface IOptionalRef { MyEnum MethodRef([In, Out, Optional, DefaultParameterValue(MyEnum.three)] ref MyEnum v); } "; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void DefaultParameterValueErrors() { string source = @" using System.Runtime.InteropServices; public enum I8 : sbyte { v = 1 } public enum U8 : byte { v = 1 } public enum I16 : short { v = 1 } public enum U16 : ushort { v = 1 } public enum I32 : int { v = 1 } public enum U32 : uint { v = 1 } public enum I64 : long { v = 1 } public enum U64 : ulong { v = 1 } public class C { } public delegate void D(); public interface I { } public struct S { } public static class ErrorCases { public static void M( // bool [Optional][DefaultParameterValue(0)] bool b1, [Optional][DefaultParameterValue(""hello"")] bool b2, // integral [Optional][DefaultParameterValue(12)] sbyte sb1, [Optional][DefaultParameterValue(""hello"")] byte by1, // char [Optional][DefaultParameterValue(""c"")] char ch1, // float [Optional][DefaultParameterValue(1.0)] float fl1, [Optional][DefaultParameterValue(1)] double dbl1, // enum [Optional][DefaultParameterValue(0)] I8 i8, [Optional][DefaultParameterValue(12)] U8 u8, [Optional][DefaultParameterValue(""hello"")] I16 i16, // string [Optional][DefaultParameterValue(5)] string str1, [Optional][DefaultParameterValue(new int[] { 12 })] string str2, // reference types [Optional][DefaultParameterValue(2)] C c1, [Optional][DefaultParameterValue(""hello"")] C c2, [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1, [DefaultParameterValue(null)] int[] arr2, [DefaultParameterValue(new int[] { 1, 2 })] object arr3, [DefaultParameterValue(typeof(object))] System.Type type1, [DefaultParameterValue(null)] System.Type type2, [DefaultParameterValue(typeof(object))] object type3, // user defined struct [DefaultParameterValue(null)] S userStruct1, [DefaultParameterValue(0)] S userStruct2, [DefaultParameterValue(""hel"")] S userStruct3, // null value to non-ref type [Optional][DefaultParameterValue(null)] bool b3, // integral [Optional][DefaultParameterValue(null)] int i2, // char [Optional][DefaultParameterValue(null)] char ch2, // float [Optional][DefaultParameterValue(null)] float fl2, // enum [Optional][DefaultParameterValue(null)] I8 i82 ) { } } "; // NOTE: anywhere dev10 reported CS1909, roslyn reports CS1910. CreateCompilation(source).VerifyDiagnostics( // (27,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(0)] bool b1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (28,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] bool b2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (31,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(12)] sbyte sb1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (32,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] byte by1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (35,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("c")] char ch1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (38,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(1.0)] float fl1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (42,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(0)] I8 i8, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (43,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(12)] U8 u8, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (44,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] I16 i16, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (47,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(5)] string str1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (48,20): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [Optional][DefaultParameterValue(new int[] { 12 })] string str2, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (51,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(2)] C c1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (52,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue("hello")] C c2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (54,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // NOTE: Roslyn specifically allows this usage (illegal in dev10). //// (55,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'int[]', unless the default value is null //// [DefaultParameterValue(null)] int[] arr2, //Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("int[]"), // (56,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(new int[] { 1, 2 })] object arr3, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (58,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(typeof(object))] System.Type type1, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"), // NOTE: Roslyn specifically allows this usage (illegal in dev10). //// (59,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'System.Type', unless the default value is null //// [DefaultParameterValue(null)] System.Type type2, //Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("System.Type"), // (60,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute // [DefaultParameterValue(typeof(object))] object type3, Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"), // (63,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue(null)] S userStruct1, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (64,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue(0)] S userStruct2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (65,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [DefaultParameterValue("hel")] S userStruct3, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (68,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] bool b3, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (71,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] int i2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (74,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] char ch2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (77,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] float fl2, Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (80,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type // [Optional][DefaultParameterValue(null)] I8 i82 Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [WorkItem(544440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544440")] [ConditionalFact(typeof(DesktopOnly))] public void TestBug12768() { string sourceDefinitions = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public class C { public static void M1(object x = null) { Console.WriteLine(x ?? 1); } public static void M2([Optional] object x) { Console.WriteLine(x ?? 2); } public static void M3([MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 3); } public static void M4([MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 4); } public static void M5([IDispatchConstant] object x = null) { Console.WriteLine(x ?? 5); } public static void M6([IDispatchConstant] [Optional] object x) { Console.WriteLine(x ?? 6); } public static void M7([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 7); } public static void M8([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 8); } public static void M9([IUnknownConstant]object x = null) { Console.WriteLine(x ?? 9); } public static void M10([IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 10); } public static void M11([IUnknownConstant][MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 11); } public static void M12([IUnknownConstant][MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 12); } public static void M13([IUnknownConstant][IDispatchConstant] object x = null) { Console.WriteLine(x ?? 13); } public static void M14([IDispatchConstant][IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 14); } public static void M15([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null) { Console.WriteLine(x ?? 15); } public static void M16([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x) { Console.WriteLine(x ?? 16); } public static void M17([MarshalAs(UnmanagedType.Interface)][IDispatchConstant][Optional] object x) { Console.WriteLine(x ?? 17); } public static void M18([MarshalAs(UnmanagedType.Interface)][IUnknownConstant][Optional] object x) { Console.WriteLine(x ?? 18); } } "; string sourceCalls = @" internal class D { static void Main() { C.M1(); // null C.M2(); // Missing C.M3(); // null C.M4(); // null C.M5(); // null C.M6(); // DispatchWrapper C.M7(); // null C.M8(); // null C.M9(); // null C.M10(); // UnknownWrapper C.M11(); // null C.M12(); // null C.M13(); // null C.M14(); // UnknownWrapper C.M15(); // null C.M16(); // null C.M17(); // null C.M18(); // null } }"; string expected = @"1 System.Reflection.Missing 3 4 5 System.Runtime.InteropServices.DispatchWrapper 7 8 9 System.Runtime.InteropServices.UnknownWrapper 11 12 13 System.Runtime.InteropServices.UnknownWrapper 15 16 17 18"; // definitions in source: var verifier = CompileAndVerify(new[] { sourceDefinitions, sourceCalls }, expectedOutput: expected); // definitions in metadata: using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { CompileAndVerify(new[] { sourceCalls }, new[] { assembly.GetReference() }, expectedOutput: expected); } } [ConditionalFact(typeof(DesktopOnly))] public void IUnknownConstant_MissingType() { var source = @" using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { static void M0([Optional, MarshalAs(UnmanagedType.Interface)] object param) { } static void M1([Optional, IUnknownConstant] object param) { } static void M2([Optional, IDispatchConstant] object param) { } static void M3([Optional] object param) { } static void M() { M0(); M1(); M2(); M3(); } } "; CompileAndVerify(source).VerifyDiagnostics(); var comp = CreateCompilation(source); comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor); comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor); comp.MakeMemberMissing(WellKnownMember.System_Type__Missing); comp.VerifyDiagnostics( // (15,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.UnknownWrapper..ctor' // M1(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M1()").WithArguments("System.Runtime.InteropServices.UnknownWrapper", ".ctor").WithLocation(15, 9), // (16,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.DispatchWrapper..ctor' // M2(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M2()").WithArguments("System.Runtime.InteropServices.DispatchWrapper", ".ctor").WithLocation(16, 9), // (17,9): error CS0656: Missing compiler required member 'System.Type.Missing' // M3(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M3()").WithArguments("System.Type", "Missing").WithLocation(17, 9)); } [WorkItem(545329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545329")] [Fact()] public void ComOptionalRefParameter() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020813-0000-0000-c000-000000000046"")] interface ComClass { void M([Optional]ref object o); } class D : ComClass { public void M(ref object o) { } } class C { static void Main() { D d = new D(); ComClass c = d; c.M(); //fine d.M(); //CS1501 } } "; CreateCompilation(source).VerifyDiagnostics( // (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'D.M(ref object)' // d.M(); //CS1501 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "D.M(ref object)").WithLocation(25, 11)); } [WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")] [ClrOnlyFact] public void TestVbDecimalAndDateTimeDefaultParameters() { var vb = @" Imports System public Module VBModule Sub I(Optional ByVal x As System.Int32 = 456) Console.WriteLine(x) End Sub Sub NI(Optional ByVal x As System.Int32? = 457) Console.WriteLine(x) End Sub Sub OI(Optional ByVal x As Object = 458 ) Console.WriteLine(x) End Sub Sub DA(Optional ByVal x As DateTime = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub NDT(Optional ByVal x As DateTime? = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub ODT(Optional ByVal x As Object = #1/2/2007#) Console.WriteLine(x = #1/2/2007#) End Sub Sub Dec(Optional ByVal x as Decimal = 12.3D) Console.WriteLine(x.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub NDec(Optional ByVal x as Decimal? = 12.4D) Console.WriteLine(x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub ODec(Optional ByVal x as Object = 12.5D) Console.WriteLine(DirectCast(x, Decimal).ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub End Module "; var csharp = @" using System; public class D { static void Main() { // Ensure suites run in invariant culture across machines System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; // Possible in both C# and VB: VBModule.I(); VBModule.NI(); VBModule.Dec(); VBModule.NDec(); // Not possible in C#, possible in VB, but C# honours the parameter: VBModule.OI(); VBModule.ODec(); VBModule.DA(); VBModule.NDT(); VBModule.ODT(); } } "; string expected = @"456 457 12.3 12.4 458 12.5 True True True"; string il = @"{ // Code size 181 (0xb5) .maxstack 5 IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get"" IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get"" IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set"" IL_000f: ldc.i4 0x1c8 IL_0014: call ""void VBModule.I(int)"" IL_0019: ldc.i4 0x1c9 IL_001e: newobj ""int?..ctor(int)"" IL_0023: call ""void VBModule.NI(int?)"" IL_0028: ldc.i4.s 123 IL_002a: ldc.i4.0 IL_002b: ldc.i4.0 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0033: call ""void VBModule.Dec(decimal)"" IL_0038: ldc.i4.s 124 IL_003a: ldc.i4.0 IL_003b: ldc.i4.0 IL_003c: ldc.i4.0 IL_003d: ldc.i4.1 IL_003e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0043: newobj ""decimal?..ctor(decimal)"" IL_0048: call ""void VBModule.NDec(decimal?)"" IL_004d: ldc.i4 0x1ca IL_0052: box ""int"" IL_0057: call ""void VBModule.OI(object)"" IL_005c: ldc.i4.s 125 IL_005e: ldc.i4.0 IL_005f: ldc.i4.0 IL_0060: ldc.i4.0 IL_0061: ldc.i4.1 IL_0062: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0067: box ""decimal"" IL_006c: call ""void VBModule.ODec(object)"" IL_0071: ldc.i8 0x8c8fc181490c000 IL_007a: newobj ""System.DateTime..ctor(long)"" IL_007f: call ""void VBModule.DA(System.DateTime)"" IL_0084: ldc.i8 0x8c8fc181490c000 IL_008d: newobj ""System.DateTime..ctor(long)"" IL_0092: newobj ""System.DateTime?..ctor(System.DateTime)"" IL_0097: call ""void VBModule.NDT(System.DateTime?)"" IL_009c: ldc.i8 0x8c8fc181490c000 IL_00a5: newobj ""System.DateTime..ctor(long)"" IL_00aa: box ""System.DateTime"" IL_00af: call ""void VBModule.ODT(object)"" IL_00b4: ret }"; var vbCompilation = CreateVisualBasicCompilation("VB", vb, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbCompilation.VerifyDiagnostics(); var csharpCompilation = CreateCSharpCompilation("CS", csharp, compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new[] { vbCompilation }); var verifier = CompileAndVerify(csharpCompilation, expectedOutput: expected); verifier.VerifyIL("D.Main", il); } [WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")] [Fact] public void TestCSharpDecimalAndDateTimeDefaultParameters() { var library = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public enum E { one, two, three } public class C { public void Goo( [Optional][DateTimeConstant(100000)]DateTime dateTime, decimal dec = 12345678901234567890m, int? x = 0, int? q = null, short y = 10, int z = default(int), S? s = null) //S? s2 = default(S)) { if (dateTime == new DateTime(100000)) { Console.WriteLine(""DatesMatch""); } else { Console.WriteLine(""Dates dont match!!""); } Write(dec); Write(x); Write(q); Write(y); Write(z); Write(s); //Write(s2); } public void Bar(S? s1, S? s2, S? s3) { } public void Baz(E? e1 = E.one, long? x = 0) { if (e1.HasValue) { Console.WriteLine(e1); } else { Console.WriteLine(""null""); } Console.WriteLine(x); } public void Write(object o) { if (o == null) { Console.WriteLine(""null""); } else { Console.WriteLine(o); } } } public struct S { } "; var main = @" using System; public class D { static void Main() { // Ensure suites run in invariant culture across machines System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; C c = new C(); c.Goo(); c.Baz(); } } "; var libComp = CreateCompilation(library, options: TestOptions.ReleaseDll, assemblyName: "Library"); libComp.VerifyDiagnostics(); var exeComp = CreateCompilation(main, new[] { new CSharpCompilationReference(libComp) }, options: TestOptions.ReleaseExe, assemblyName: "Main"); var verifier = CompileAndVerify(exeComp, expectedOutput: @"DatesMatch 12345678901234567890 0 null 10 0 null one 0"); verifier.VerifyIL("D.Main", @"{ // Code size 97 (0x61) .maxstack 9 .locals init (int? V_0, S? V_1) IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get"" IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get"" IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set"" IL_000f: newobj ""C..ctor()"" IL_0014: dup IL_0015: ldc.i4 0x186a0 IL_001a: conv.i8 IL_001b: newobj ""System.DateTime..ctor(long)"" IL_0020: ldc.i8 0xab54a98ceb1f0ad2 IL_0029: newobj ""decimal..ctor(ulong)"" IL_002e: ldc.i4.0 IL_002f: newobj ""int?..ctor(int)"" IL_0034: ldloca.s V_0 IL_0036: initobj ""int?"" IL_003c: ldloc.0 IL_003d: ldc.i4.s 10 IL_003f: ldc.i4.0 IL_0040: ldloca.s V_1 IL_0042: initobj ""S?"" IL_0048: ldloc.1 IL_0049: callvirt ""void C.Goo(System.DateTime, decimal, int?, int?, short, int, S?)"" IL_004e: ldc.i4.0 IL_004f: newobj ""E?..ctor(E)"" IL_0054: ldc.i4.0 IL_0055: conv.i8 IL_0056: newobj ""long?..ctor(long)"" IL_005b: callvirt ""void C.Baz(E?, long?)"" IL_0060: ret }"); } [Fact] public void OmittedComOutParameter() { // We allow omitting optional ref arguments but not optional out arguments. var source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""989FE455-5A6D-4D05-A349-1A221DA05FDA"")] interface I { void M([Optional]out object o); } class P { static void Q(I i) { i.M(); } } "; // Note that the native compiler gives a slightly less informative error message here. var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,26): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'I.M(out object)' // static void Q(I i) { i.M(); } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "I.M(out object)") ); } [Fact] public void OmittedComRefParameter() { var source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""A8FAF53B-F502-4465-9429-CAB2A19B47BE"")] interface ICom { void M(out int w, int x, [Optional]ref object o, int z = 0); } class Com : ICom { public void M(out int w, int x, ref object o, int z) { w = 123; Console.WriteLine(x); if (o != null) { Console.WriteLine(o.GetType()); } else { Console.WriteLine(""null""); } Console.WriteLine(z); } static void Main() { ICom c = new Com(); int q; c.M(w: out q, z: 10, x: 100); Console.WriteLine(q); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" 100 System.Reflection.Missing 10 123"); verifier.VerifyIL("Com.Main", @" { // Code size 31 (0x1f) .maxstack 5 .locals init (int V_0, //q object V_1) IL_0000: newobj ""Com..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 100 IL_0009: ldsfld ""object System.Type.Missing"" IL_000e: stloc.1 IL_000f: ldloca.s V_1 IL_0011: ldc.i4.s 10 IL_0013: callvirt ""void ICom.M(out int, int, ref object, int)"" IL_0018: ldloc.0 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ret }"); } [Fact] public void ArrayElementComRefParameter() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")] interface IA { void M(ref int i); } class A : IA { void IA.M(ref int i) { i += 2; } } class B { static void M(IA a) { a.M(F()[0]); } static void MByRef(IA a) { a.M(ref F()[0]); } static int[] i = { 0 }; static int[] F() { Console.WriteLine(""F()""); return i; } static void Main() { IA a = new A(); M(a); ReportAndReset(); MByRef(a); ReportAndReset(); } static void ReportAndReset() { Console.WriteLine(""{0}"", i[0]); i = new[] { 0 }; } }"; var verifier = CompileAndVerify(source, expectedOutput: @"F() 0 F() 2"); verifier.VerifyIL("B.M(IA)", @"{ // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""int[] B.F()"" IL_0006: ldc.i4.0 IL_0007: ldelem.i4 IL_0008: stloc.0 IL_0009: ldloca.s V_0 IL_000b: callvirt ""void IA.M(ref int)"" IL_0010: ret }"); verifier.VerifyIL("B.MByRef(IA)", @"{ // Code size 18 (0x12) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int[] B.F()"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: callvirt ""void IA.M(ref int)"" IL_0011: ret }"); } [Fact] public void ArrayElementComRefParametersReordered() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")] interface IA { void M(ref int x, ref int y); } class A : IA { void IA.M(ref int x, ref int y) { x += 2; y += 3; } } class B { static void M(IA a) { a.M(y: ref F2()[0], x: ref F1()[0]); } static int[] i1 = { 0 }; static int[] i2 = { 0 }; static int[] F1() { Console.WriteLine(""F1()""); return i1; } static int[] F2() { Console.WriteLine(""F2()""); return i2; } static void Main() { IA a = new A(); M(a); Console.WriteLine(""{0}, {1}"", i1[0], i2[0]); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"F2() F1() 2, 3 "); verifier.VerifyIL("B.M(IA)", @"{ // Code size 31 (0x1f) .maxstack 3 .locals init (int& V_0) IL_0000: ldarg.0 IL_0001: call ""int[] B.F2()"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: stloc.0 IL_000d: call ""int[] B.F1()"" IL_0012: ldc.i4.0 IL_0013: ldelema ""int"" IL_0018: ldloc.0 IL_0019: callvirt ""void IA.M(ref int, ref int)"" IL_001e: ret }"); } [Fact] [WorkItem(546713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546713")] public void Test16631() { var source = @" public abstract class B { protected abstract void E<T>(); } public class D : B { void M() { // There are two possible methods to choose here. The static method // is better because it is declared in a more derived class; the // virtual method is better because it has exactly the right number // of parameters. In this case, the static method wins. The virtual // method is to be treated as though it was a method of the base class, // and therefore automatically loses. (The bug we are regressing here // is that Roslyn did not correctly identify the originally-defining // type B when the method E was generic. The original repro scenario in // bug 16631 was much more complicated than this, but it boiled down to // overload resolution choosing the wrong method.) E<int>(); } protected override void E<T>() { System.Console.WriteLine(1); } static void E<T>(int x = 0xBEEF) { System.Console.WriteLine(2); } static void Main() { (new D()).M(); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyIL("D.M()", @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldc.i4 0xbeef IL_0005: call ""void D.E<int>(int)"" IL_000a: ret }"); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_PrimitiveStruct() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(int p) { } public void M1(int p = 0) { } // default of type public void M2(int p = 1) { } // not default of type public void M3([Optional]int p) { } // no default specified (would be illegal) public void M4([DefaultParameterValue(0)]int p) { } // default of type, not optional public void M5([DefaultParameterValue(1)]int p) { } // not default of type, not optional public void M6([Optional][DefaultParameterValue(0)]int p) { } // default of type, optional public void M7([Optional][DefaultParameterValue(1)]int p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal(0, parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0), parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal(1, parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.True(parameters[4].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create(0), parameters[4].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length); Assert.False(parameters[5].IsOptional); Assert.False(parameters[5].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue); Assert.True(parameters[5].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create(1), parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[5].GetAttributes().Length); Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(0, parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal(1, parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1), parameters[7].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_UserDefinedStruct() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(S p) { } public void M1(S p = default(S)) { } public void M2([Optional]S p) { } // no default specified (would be illegal) } public struct S { public int x; } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(3, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.False(parameters[2].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length); }; // TODO: RefEmit doesn't emit the default value of M1's parameter. CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_String() { var source = @" using System; using System.Runtime.InteropServices; public class C { public void M0(string p) { } public void M1(string p = null) { } public void M2(string p = ""A"") { } public void M3([Optional]string p) { } // no default specified (would be illegal) public void M4([DefaultParameterValue(null)]string p) { } public void M5([Optional][DefaultParameterValue(null)]string p) { } public void M6([DefaultParameterValue(""A"")]string p) { } public void M7([Optional][DefaultParameterValue(""A"")]string p) { } } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal("A", parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create("A"), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.True(parameters[4].HasMetadataConstantValue); Assert.Equal(ConstantValue.Null, parameters[4].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length); Assert.True(parameters[5].IsOptional); Assert.True(parameters[5].HasExplicitDefaultValue); Assert.Null(parameters[5].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); Assert.False(parameters[6].IsOptional); Assert.False(parameters[6].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[6].ExplicitDefaultValue); Assert.True(parameters[6].HasMetadataConstantValue); Assert.Equal(ConstantValue.Create("A"), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[6].GetAttributes().Length); Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal("A", parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create("A"), parameters[7].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_Decimal() { var source = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C { public void M0(decimal p) { } public void M1(decimal p = 0) { } // default of type public void M2(decimal p = 1) { } // not default of type public void M3([Optional]decimal p) { } // no default specified (would be illegal) public void M4([DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, not optional public void M5([DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, not optional public void M6([Optional][DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, optional public void M7([Optional][DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(8, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal(0M, parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0M), parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); Assert.True(parameters[2].IsOptional); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Equal(1M, parameters[2].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1M), parameters[2].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[2].GetAttributes().Length); Assert.True(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length); Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.False(parameters[4].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(0M) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[4].GetAttributes().Length); // DecimalConstantAttribute Assert.False(parameters[5].IsOptional); Assert.False(parameters[5].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue); Assert.False(parameters[5].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(1M) : null, parameters[5].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[5].GetAttributes().Length); // DecimalConstantAttribute Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(0M, parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(0M), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute Assert.True(parameters[7].IsOptional); Assert.True(parameters[7].HasExplicitDefaultValue); Assert.Equal(1M, parameters[7].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(1M), parameters[7].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")] public void IsOptionalVsHasDefaultValue_DateTime() { var source = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C { public void M0(DateTime p) { } public void M1(DateTime p = default(DateTime)) { } public void M2([Optional]DateTime p) { } // no default specified (would be illegal) public void M3([DateTimeConstant(0)]DateTime p) { } // default of type, not optional public void M4([DateTimeConstant(1)]DateTime p) { } // not default of type, not optional public void M5([Optional][DateTimeConstant(0)]DateTime p) { } // default of type, optional public void M6([Optional][DateTimeConstant(1)]DateTime p) { } // not default of type, optional } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(7, methods.Length); var parameters = methods.Select(m => m.Parameters.Single()).ToArray(); Assert.False(parameters[0].IsOptional); Assert.False(parameters[0].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue); Assert.Null(parameters[0].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.True(parameters[1].IsOptional); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Null(parameters[1].ExplicitDefaultValue); Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue); Assert.Equal(0, parameters[1].GetAttributes().Length); // As in dev11, [DateTimeConstant] is not emitted in this case. Assert.True(parameters[2].IsOptional); Assert.False(parameters[2].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length); Assert.False(parameters[3].IsOptional); Assert.False(parameters[3].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue); Assert.False(parameters[3].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(0)) : null, parameters[3].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[3].GetAttributes().Length); // DateTimeConstant Assert.False(parameters[4].IsOptional); Assert.False(parameters[4].HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue); Assert.False(parameters[4].HasMetadataConstantValue); Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(1)) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter Assert.Equal(1, parameters[4].GetAttributes().Length); // DateTimeConstant Assert.True(parameters[5].IsOptional); Assert.True(parameters[5].HasExplicitDefaultValue); Assert.Equal(new DateTime(0), parameters[5].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(new DateTime(0)), parameters[5].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant Assert.True(parameters[6].IsOptional); Assert.True(parameters[6].HasExplicitDefaultValue); Assert.Equal(new DateTime(1), parameters[6].ExplicitDefaultValue); Assert.Equal(ConstantValue.Create(new DateTime(1)), parameters[6].ExplicitDefaultConstantValue); Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant }; // TODO: Guess - RefEmit doesn't like DateTime constants. CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] public void InvalidConversionForDefaultArgument_InIL() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method P::.ctor .method public hidebysig instance int32 M1([opt] int32 s) cil managed { .param [1] = ""abc"" // Code size 2 (0x2) .maxstack 8 IL_0000: ldarg.1 IL_0001: ret } // end of method P::M1 } // end of class P "; var csharp = @" class C { public static void Main() { P p = new P(); System.Console.Write(p.M1()); } } "; var comp = CreateCompilationWithIL(csharp, il, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,31): error CS0029: Cannot implicitly convert type 'string' to 'int' // System.Console.Write(p.M1()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 31)); } [Fact] public void DefaultArgument_LoopInUsage() { var csharp = @" class C { static object F(object param = F()) => param; // 1 } "; var comp = CreateCompilation(csharp); comp.VerifyDiagnostics( // (4,36): error CS1736: Default parameter value for 'param' must be a compile-time constant // static object F(object param = F()) => param; // 1 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("param").WithLocation(4, 36)); var method = comp.GetMember<MethodSymbol>("C.F"); var param = method.Parameters.Single(); Assert.Equal(ConstantValue.Bad, param.ExplicitDefaultConstantValue); } [Fact] public void DefaultValue_Boxing() { var csharp = @" class C { void M1(object obj = 1) // 1 { } C(object obj = System.DayOfWeek.Monday) // 2 { } } "; var comp = CreateCompilation(csharp); comp.VerifyDiagnostics( // (4,20): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // void M1(object obj = 1) // 1 Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(4, 20), // (8,14): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // C(object obj = System.DayOfWeek.Monday) // 2 Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(8, 14)); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./docs/wiki/Getting-Started-on-Visual-Studio-2015-Preview.md
1. Set up a box with Visual Studio 2015 Preview. Either [install Visual Studio 2015 Preview](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 Preview SDK](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](http://visualstudiogallery.msdn.microsoft.com/849f3ab1-05cf-4682-b4af-ef995e2aa1a5) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](http://visualstudiogallery.msdn.microsoft.com/70e184da-9b3a-402f-b210-d62a898e2887) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
1. Set up a box with Visual Studio 2015 Preview. Either [install Visual Studio 2015 Preview](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 Preview SDK](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](http://visualstudiogallery.msdn.microsoft.com/849f3ab1-05cf-4682-b4af-ef995e2aa1a5) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](http://visualstudiogallery.msdn.microsoft.com/70e184da-9b3a-402f-b210-d62a898e2887) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./docs/features/async-main.md
# Async Task Main ## [dotnet/csharplang proposal](https://github.com/dotnet/csharplang/blob/main/proposals/async-main.md) ## Technical Details * The compiler must recognize `Task` and `Task<int>` as valid entrypoint return types in addition to `void` and `int`. * The compiler must allow `async` to be placed on a main method that returns a `Task` or a `Task<T>` (but not void). * The compiler must generate a shim method `$EntrypointMain` that mimics the arguments of the user-defined main. * `static async Task Main(...)` -> `static void $EntrypointMain(...)` * `static async Task<int> Main(...)` -> `static int $EntrypointMain(...)` * The parameters between the user-defined main and the generated main should match exactly. * The body of the generated main should be `return Main(args...).GetAwaiter().GetResult();`
# Async Task Main ## [dotnet/csharplang proposal](https://github.com/dotnet/csharplang/blob/main/proposals/async-main.md) ## Technical Details * The compiler must recognize `Task` and `Task<int>` as valid entrypoint return types in addition to `void` and `int`. * The compiler must allow `async` to be placed on a main method that returns a `Task` or a `Task<T>` (but not void). * The compiler must generate a shim method `$EntrypointMain` that mimics the arguments of the user-defined main. * `static async Task Main(...)` -> `static void $EntrypointMain(...)` * `static async Task<int> Main(...)` -> `static int $EntrypointMain(...)` * The parameters between the user-defined main and the generated main should match exactly. * The body of the generated main should be `return Main(args...).GetAwaiter().GetResult();`
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarItem.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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { internal abstract class NavigationBarItem : IEquatable<NavigationBarItem> { public string Text { get; } public Glyph Glyph { get; } public bool Bolded { get; } public bool Grayed { get; } public int Indent { get; } public ImmutableArray<NavigationBarItem> ChildItems { get; } /// <summary> /// The spans in the owning document corresponding to this nav bar item. If the user's caret enters one of /// these spans, we'll select that item in the nav bar (except if they're in an item's span that is nested /// within this). /// </summary> /// <remarks>This can be empty for items whose location is in another document.</remarks> public ImmutableArray<TextSpan> Spans { get; } /// <summary> /// The span in the owning document corresponding to where to navigate to if the user selects this item in the /// drop down. /// </summary> /// <remarks>This can be <see langword="null"/> for items whose location is in another document.</remarks> public TextSpan? NavigationSpan { get; } internal ITextVersion? TextVersion { get; } public NavigationBarItem( ITextVersion? textVersion, string text, Glyph glyph, ImmutableArray<TextSpan> spans, TextSpan? navigationSpan, ImmutableArray<NavigationBarItem> childItems = default, int indent = 0, bool bolded = false, bool grayed = false) { TextVersion = textVersion; Text = text; Glyph = glyph; Spans = spans; NavigationSpan = navigationSpan; ChildItems = childItems.NullToEmpty(); Indent = indent; Bolded = bolded; Grayed = grayed; } public TextSpan? TryGetNavigationSpan(ITextVersion textVersion) { if (this.NavigationSpan == null) return null; return this.TextVersion!.CreateTrackingSpan(this.NavigationSpan.Value.ToSpan(), SpanTrackingMode.EdgeExclusive) .GetSpan(textVersion).ToTextSpan(); } public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); public bool Equals(NavigationBarItem? other) { return other != null && Text == other.Text && Glyph == other.Glyph && Bolded == other.Bolded && Grayed == other.Grayed && Indent == other.Indent && ChildItems.SequenceEqual(other.ChildItems) && Spans.SequenceEqual(other.Spans) && EqualityComparer<TextSpan?>.Default.Equals(NavigationSpan, other.NavigationSpan); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { internal abstract class NavigationBarItem : IEquatable<NavigationBarItem> { public string Text { get; } public Glyph Glyph { get; } public bool Bolded { get; } public bool Grayed { get; } public int Indent { get; } public ImmutableArray<NavigationBarItem> ChildItems { get; } /// <summary> /// The spans in the owning document corresponding to this nav bar item. If the user's caret enters one of /// these spans, we'll select that item in the nav bar (except if they're in an item's span that is nested /// within this). /// </summary> /// <remarks>This can be empty for items whose location is in another document.</remarks> public ImmutableArray<TextSpan> Spans { get; } /// <summary> /// The span in the owning document corresponding to where to navigate to if the user selects this item in the /// drop down. /// </summary> /// <remarks>This can be <see langword="null"/> for items whose location is in another document.</remarks> public TextSpan? NavigationSpan { get; } internal ITextVersion? TextVersion { get; } public NavigationBarItem( ITextVersion? textVersion, string text, Glyph glyph, ImmutableArray<TextSpan> spans, TextSpan? navigationSpan, ImmutableArray<NavigationBarItem> childItems = default, int indent = 0, bool bolded = false, bool grayed = false) { TextVersion = textVersion; Text = text; Glyph = glyph; Spans = spans; NavigationSpan = navigationSpan; ChildItems = childItems.NullToEmpty(); Indent = indent; Bolded = bolded; Grayed = grayed; } public TextSpan? TryGetNavigationSpan(ITextVersion textVersion) { if (this.NavigationSpan == null) return null; return this.TextVersion!.CreateTrackingSpan(this.NavigationSpan.Value.ToSpan(), SpanTrackingMode.EdgeExclusive) .GetSpan(textVersion).ToTextSpan(); } public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); public bool Equals(NavigationBarItem? other) { return other != null && Text == other.Text && Glyph == other.Glyph && Bolded == other.Bolded && Grayed == other.Grayed && Indent == other.Indent && ChildItems.SequenceEqual(other.ChildItems) && Spans.SequenceEqual(other.Spans) && EqualityComparer<TextSpan?>.Default.Equals(NavigationSpan, other.NavigationSpan); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/VisualBasicTest/Recommendations/Queries/WhereKeywordRecommenderTests.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.Queries Public Class WhereKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Where") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z |</MethodBody>, "Where") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Where") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Where") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Where") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterEOLTest() VerifyRecommendationsContain( <MethodBody> Dim q1 = From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereMissingAfterTwoEOLTest() VerifyRecommendationsMissing( <MethodBody> Dim q1 = From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereMissingAfterTwoEOLWithLineContinuationTest() VerifyRecommendationsMissing( <MethodBody> Dim q1 = From i4 In arr _ |</MethodBody>, "Where") 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.Queries Public Class WhereKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Where") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z |</MethodBody>, "Where") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Where") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Where") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Where") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereAfterEOLTest() VerifyRecommendationsContain( <MethodBody> Dim q1 = From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereMissingAfterTwoEOLTest() VerifyRecommendationsMissing( <MethodBody> Dim q1 = From i4 In arr |</MethodBody>, "Where") End Sub <WorkItem(531545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531545")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WhereMissingAfterTwoEOLWithLineContinuationTest() VerifyRecommendationsMissing( <MethodBody> Dim q1 = From i4 In arr _ |</MethodBody>, "Where") End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ExpansionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ExpansionTests : Inherits VisualBasicResultProviderTestBase <Fact> Public Sub Enums() Dim source = " Imports System Enum E A B End Enum Enum F As Byte A = 42 End Enum <Flags> Enum [if] [else] = 1 fi End Enum Class C Dim e As E = E.B Dim f As F = Nothing Dim g As [if] = [if].else Or [if].fi Dim h As [if] = 5 End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim rootExpr = "New C()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("e", "B {1}", "E", "(New C()).e", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.B"), EvalResult("f", "0", "F", "(New C()).f", DkmEvaluationResultFlags.CanFavorite, editableValue:="0"), EvalResult("g", "else Or fi {3}", "if", "(New C()).g", DkmEvaluationResultFlags.CanFavorite, editableValue:="[if].else Or [if].fi"), EvalResult("h", "5", "if", "(New C()).h", DkmEvaluationResultFlags.CanFavorite, editableValue:="5")) End Sub <Fact> Public Sub Nullable() Dim source = " Enum E A End Enum Structure S Friend Sub New(f as Integer) Me.F = f End Sub Dim F As Object End Structure Class C Dim e1 As E? = E.A Dim e2 As E? = Nothing Dim s1 As S? = New S(1) Dim s2 As S? = Nothing Dim o1 As Object = New System.Nullable(Of S)(Nothing) Dim o2 As Object = New System.Nullable(Of S)() End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim rootExpr = "New C()" Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("e1", "A {0}", "E?", "(New C()).e1", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.A"), EvalResult("e2", "Nothing", "E?", "(New C()).e2", DkmEvaluationResultFlags.CanFavorite), EvalResult("o1", "{S}", "Object {S}", "(New C()).o1", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("o2", "Nothing", "Object", "(New C()).o2", DkmEvaluationResultFlags.CanFavorite), EvalResult("s1", "{S}", "S?", "(New C()).s1", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("s2", "Nothing", "S?", "(New C()).s2", DkmEvaluationResultFlags.CanFavorite)) ' Dim o1 As Object = New System.Nullable(Of S)(Nothing) Verify(GetChildren(children(2)), EvalResult("F", "Nothing", "Object", "DirectCast((New C()).o1, S).F", DkmEvaluationResultFlags.CanFavorite)) ' Dim s1 As S? = New S(1) Verify(GetChildren(children(4)), EvalResult("F", "1", "Object {Integer}", "(New C()).s1.F", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub Pointers() Dim source = ".class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .field private int32* p .field private int32* q .method assembly hidebysig specialname rtspecialname instance void .ctor(native int p) cil managed { // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call void* [mscorlib]System.IntPtr::op_Explicit(native int) IL_000f: stfld int32* C::p IL_0014: ret } }" Dim assembly = GetAssemblyFromIL(source) Dim type = assembly.GetType("C") Dim p = GCHandle.Alloc(4, GCHandleType.Pinned).AddrOfPinnedObject() Dim rootExpr = String.Format("new C({0})", p) Dim value = CreateDkmClrValue(ReflectionUtilities.Instantiate(type, p)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("p", PointerToString(p), "Integer*", String.Format("({0}).p", rootExpr), DkmEvaluationResultFlags.Expandable), EvalResult("q", PointerToString(IntPtr.Zero), "Integer*", String.Format("({0}).q", rootExpr))) Dim fullName = String.Format("*({0}).p", rootExpr) Verify(GetChildren(children(0)), EvalResult(fullName, "4", "Integer", fullName, DkmEvaluationResultFlags.None)) End Sub <Fact> Public Sub StaticMembers() Dim source = "Class A Const F As Integer = 1 Shared ReadOnly G As Integer = 2 End Class Class B : Inherits A End Class Structure S Const F As Object = Nothing Shared ReadOnly Property P As Object Get Return 3 End Get End Property End Structure Enum E A B End Enum Class C Dim a As A = Nothing Dim b As B = Nothing Dim s As New S() Dim sn? As S = Nothing Dim e As E = E.B End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim rootExpr = "New C()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("a", "Nothing", "A", "(New C()).a", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("b", "Nothing", "B", "(New C()).b", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("e", "B {1}", "E", "(New C()).e", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.B"), EvalResult("s", "{S}", "S", "(New C()).s", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("sn", "Nothing", "S?", "(New C()).sn", DkmEvaluationResultFlags.CanFavorite)) ' Dim a As A = Nothing Dim more = GetChildren(children(0)) Verify(more, EvalResult("Shared members", Nothing, "", "A", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) more = GetChildren(more(0)) Verify(more, EvalResult("F", "1", "Integer", "A.F", DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "2", "Integer", "A.G", DkmEvaluationResultFlags.ReadOnly)) ' Dim s As New S() more = GetChildren(children(3)) Verify(more, EvalResult("Shared members", Nothing, "", "S", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) more = GetChildren(more(0)) Verify(more, EvalResult("F", "Nothing", "Object", "S.F", DkmEvaluationResultFlags.ReadOnly), EvalResult("P", "3", "Object {Integer}", "S.P", DkmEvaluationResultFlags.ReadOnly)) End Sub <Fact> Public Sub DeclaredTypeObject_Array() Dim source = " Interface I Property Q As Integer End Interface Class A Friend F As Object End Class Class B : Inherits A : Implements I Friend Sub New(f As Object) Me.F = f End Sub Friend ReadOnly Property P As Object Get Return Me.F End Get End Property Property Q As Integer Implements I.Q Get End Get Set End Set End Property End Class Class C Dim a() As A = { New B(1) } Dim b() As B = { New B(2) } Dim i() As I = { New B(3) } Dim o() As Object = { New B(4) } End Class " Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim children = GetChildren(FormatResult("c", CreateDkmClrValue(Activator.CreateInstance(typeC)))) Verify(children, EvalResult("a", "{Length=1}", "A()", "c.a", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("b", "{Length=1}", "B()", "c.b", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("i", "{Length=1}", "I()", "c.i", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("o", "{Length=1}", "Object()", "c.o", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(0)).Single()), ' as A() EvalResult("F", "1", "Object {Integer}", "c.a(0).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "1", "Object {Integer}", "DirectCast(c.a(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.a(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(1)).Single()), ' as B() EvalResult("F", "2", "Object {Integer}", "c.b(0).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "2", "Object {Integer}", "c.b(0).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "c.b(0).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(2)).Single()), ' as I() EvalResult("F", "3", "Object {Integer}", "DirectCast(c.i(0), A).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "3", "Object {Integer}", "DirectCast(c.i(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.i(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(3)).Single()), ' as Object() EvalResult("F", "4", "Object {Integer}", "DirectCast(c.o(0), A).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "4", "Object {Integer}", "DirectCast(c.o(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.o(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub MultilineString() Dim str = vbCrLf & "line1" & vbCrLf & "line2" Dim quotedStr = "vbCrLf & ""line1"" & vbCrLf & ""line2""" Dim value = CreateDkmClrValue(str, evalFlags:=DkmEvaluationResultFlags.RawString) Dim result = FormatResult("str", value) Verify(result, EvalResult("str", quotedStr, "String", "str", DkmEvaluationResultFlags.RawString, editableValue:=quotedStr)) End Sub <Fact> Public Sub UnicodeChar() ' This Char is printable, so we expect the EditableValue to just be the Char. Dim c = ChrW(&H1234) Dim quotedChar = """" & c & """c" Dim value = CreateDkmClrValue(c) Dim result = FormatResult("c", value) Verify(result, EvalResult("c", quotedChar, "Char", "c", editableValue:=quotedChar)) ' This Char is not printable, so we expect the EditableValue to be the "ChrW" representation. quotedChar = "ChrW(&H7)" value = CreateDkmClrValue(ChrW(&H0007)) result = FormatResult("c", value, inspectionContext:=CreateDkmInspectionContext(radix:=16)) Verify(result, EvalResult("c", quotedChar, "Char", "c", editableValue:=quotedChar)) End Sub <Fact> Public Sub UnicodeString() Const quotedString = """" & ChrW(&H1234) & """ & ChrW(7)" Dim value = CreateDkmClrValue(New String({ChrW(&H1234), ChrW(&H0007)})) Dim result = FormatResult("s", value) Verify(result, EvalResult("s", quotedString, "String", "s", editableValue:=quotedString, flags:=DkmEvaluationResultFlags.RawString)) End Sub <Fact, WorkItem(1002381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1002381")> Public Sub BaseTypeEditableValue() Dim source = " Imports System Imports System.Collections.Generic <Flags> Enum E A = 1 B = 2 End Enum Class C Dim s1 As IEnumerable(Of Char) = String.Empty Dim d1 As Object = 1D Dim e1 As ValueType = E.A Or E.B End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult("o", value) Verify(result, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("d1", "1", "Object {Decimal}", "o.d1", DkmEvaluationResultFlags.CanFavorite, editableValue:="1D"), EvalResult("e1", "A Or B {3}", "System.ValueType {E}", "o.e1", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.A Or E.B"), EvalResult("s1", """""", "System.Collections.Generic.IEnumerable(Of Char) {String}", "o.s1", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""""")) End Sub ''' <summary> ''' Hide members that have compiler-generated names. ''' </summary> ''' <remarks> ''' As in dev11, the FullName expressions don't parse. ''' </remarks> <Fact, WorkItem(1010498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010498")> Public Sub HiddenMembers() Dim source = ".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .field public object '@' .field public object '<' .field public static object '>' .field public static object '><' .field public object '<>' .field public object '1<>' .field public object '<2' .field public object '<>__' .field public object '<>k' .field public static object '<3>k' .field public static object '<<>>k' .field public static object '<>>k' .field public static object '<<>k' .field public static object '< >k' .field public object 'CS$' .field public object 'CS$<>0_' .field public object 'CS$<>7__8' .field public object 'CS$$<>7__8' .field public object 'CS<>7__8' .field public static object '$<>7__8' .field public static object 'CS$<M>7' } .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance object '<>k__get'() { ldnull ret } .method public static object '<M>7__get'() { ldnull ret } .property instance object '@'() { .get instance object B::'<>k__get'() } .property instance object '<'() { .get instance object B::'<>k__get'() } .property object '>'() { .get object B::'<M>7__get'() } .property object '><'() { .get object B::'<M>7__get'() } .property instance object '<>'() { .get instance object B::'<>k__get'() } .property instance object '1<>'() { .get instance object B::'<>k__get'() } .property instance object '<2'() { .get instance object B::'<>k__get'() } .property instance object '<>__'() { .get instance object B::'<>k__get'() } .property instance object '<>k'() { .get instance object B::'<>k__get'() } .property object '<3>k'() { .get object B::'<M>7__get'() } .property object '<<>>k'() { .get object B::'<M>7__get'() } .property object '<>>k'() { .get object B::'<M>7__get'() } .property object '<<>k'() { .get object B::'<M>7__get'() } .property object '< >k'() { .get object B::'<M>7__get'() } .property instance object 'VB$'() { .get instance object B::'<>k__get'() } .property instance object 'VB$<>0_'() { .get instance object B::'<>k__get'() } .property instance object 'VB$Me<>7__8'() { .get instance object B::'<>k__get'() } .property instance object 'VB$$<>7__8'() { .get instance object B::'<>k__get'() } .property instance object 'VB<>7__8'() { .get instance object B::'<>k__get'() } .property object '$<>7__8'() { .get object B::'<M>7__get'() } .property object 'CS$<M>7'() { .get object B::'<M>7__get'() } }" Dim assemblyBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing CommonTestBase.EmitILToArray(source, appendDefaultHeader:=True, includePdb:=False, assemblyBytes:=assemblyBytes, pdbBytes:=pdbBytes) Dim assembly = ReflectionUtilities.Load(assemblyBytes) Dim type = assembly.GetType("A") Dim rootExpr = "New A()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{A}", "A", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("1<>", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("@", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("CS<>7__8", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "A", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) children = GetChildren(children(children.Length - 1)) Verify(children, EvalResult(">", "Nothing", "Object", fullName:=Nothing), EvalResult("><", "Nothing", "Object", fullName:=Nothing)) type = assembly.GetType("B") rootExpr = "New B()" value = CreateDkmClrValue(Activator.CreateInstance(type)) result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable)) children = GetChildren(result) Verify(children, EvalResult("1<>", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("@", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("VB<>7__8", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "B", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) children = GetChildren(children(children.Length - 1)) Verify(children, EvalResult(">", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly), EvalResult("><", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly)) End Sub <Fact, WorkItem(965892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965892")> Public Sub DeclaredTypeAndRuntimeTypeDifferent() Dim source = " Class A End Class Class B : Inherits A End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("B") Dim declaredType = assembly.GetType("A") Dim value = CreateDkmClrValue(Activator.CreateInstance(type), type) Dim result = FormatResult("a", value, New DkmClrType(CType(declaredType, TypeImpl))) Verify(result, EvalResult("a", "{B}", "A {B}", "a", DkmEvaluationResultFlags.None)) Dim children = GetChildren(result) Verify(children) End Sub <Fact> Public Sub NameConflictsWithFieldOnBase() Dim source = " Class A Private f As Integer End Class Class B : Inherits A Friend f As Double End Class" Dim assembly = GetAssembly(source) Dim typeB = assembly.GetType("B") Dim instanceB = Activator.CreateInstance(typeB) Dim value = CreateDkmClrValue(instanceB, typeB) Dim result = FormatResult("b", value) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(b, A).f"), EvalResult("f", "0", "Double", "b.f", DkmEvaluationResultFlags.CanFavorite)) Dim typeA = assembly.GetType("A") value = CreateDkmClrValue(instanceB, typeB) result = FormatResult("a", value, New DkmClrType(CType(typeA, TypeImpl))) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "a.f"), EvalResult("f", "0", "Double", "DirectCast(a, B).f", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithFieldsOnMultipleBase() Dim source = " Class A Private f As Integer End Class Class B : Inherits A Friend f As Double End Class Class C : Inherits B End Class" Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(typeC) Dim value = CreateDkmClrValue(instanceC, typeC) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(c, A).f"), EvalResult("f", "0", "Double", "c.f", DkmEvaluationResultFlags.CanFavorite)) Dim typeB = assembly.GetType("B") value = CreateDkmClrValue(instanceC, typeC) result = FormatResult("b", value, New DkmClrType(CType(typeB, TypeImpl))) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(b, A).f"), EvalResult("f", "0", "Double", "b.f", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithPropertyOnNestedBase() Dim source = " Class A Private Property P As Integer Class B : Inherits A Friend Property P As Double End Class End Class Class C : Inherits A.B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("P (A)", "0", "Integer", "DirectCast(c, A).P"), EvalResult("P", "0", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A)", "0", "Integer", "DirectCast(c, A)._P"), EvalResult("_P", "0", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithPropertyOnGenericBase() Dim source = " Class A(Of T) Public Property P As T End Class Class B : Inherits A(Of Integer) Private Property P As Double End Class Class C : Inherits B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("P (A(Of Integer))", "0", "Integer", "DirectCast(c, A(Of Integer)).P"), EvalResult("P", "0", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A(Of Integer))", "0", "Integer", "DirectCast(c, A(Of Integer))._P"), EvalResult("_P", "0", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub PropertyNameConflictsWithFieldOnBase() Dim source = " Class A Public F As String End Class Class B : Inherits A Private Property F As Double End Class Class C : Inherits B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("F (A)", "Nothing", "String", "DirectCast(c, A).F"), EvalResult("F", "0", "Double", "c.F", DkmEvaluationResultFlags.CanFavorite), EvalResult("_F", "0", "Double", "c._F", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithIndexerOnBase() Dim source = " Class A Public ReadOnly Property P(x As String) As String Get Return ""DeriveMe"" End Get End Property End Class Class B : Inherits A Public Property P As String = ""Derived"" End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("B") Dim instanceB = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceB, type) Dim result = FormatResult("b", value) Verify(GetChildren(result), EvalResult("P", """Derived""", "String", "b.P", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""Derived"""), EvalResult("_P", """Derived""", "String", "b._P", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""Derived""")) End Sub <Fact> Public Sub NameConflictsWithPropertyHiddenByNameOnBase() Dim source = " Class A Shared S As Integer = 42 Friend Overridable Property p As Integer = 43 End Class Class B : Inherits A Friend Overrides Property P As Integer = 45 End Class Class C : Inherits B Shadows Property P As Double = 4.4 End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Dim children = GetChildren(result) ' TODO: Name hiding across overrides should be case-insensitive in VB, ' so "p" in this case should be hidden by "P" (and we need to qualify "p" ' with the type name "B" To disambiguate). However, we also need to ' support multiple members on the same type that differ only by case ' (properties in C# that have the same name as their backing field, etc). Verify(children, EvalResult("P", "4.4", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (B)", "45", "Integer", "DirectCast(c, B)._P"), EvalResult("_P", "4.4", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_p", "0", "Integer", "c._p", DkmEvaluationResultFlags.CanFavorite), EvalResult("p", "45", "Integer", "c.p", DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "C", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) Verify(GetChildren(children(5)), EvalResult("S", "42", "Integer", "A.S")) End Sub <Fact, WorkItem(1074435, "DevDiv")> Public Sub NameConflictsWithInterfaceReimplementation() Dim source = " Interface I ReadOnly Property P As Integer End Interface Class A : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 1 End Get End Property End Class Class B : Inherits A : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 2 End Get End Property End Class Class C : Inherits B : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 3 End Get End Property End Class " Dim assembly = GetAssembly(source) Dim typeB = assembly.GetType("B") Dim typeC = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(typeC) Dim value = CreateDkmClrValue(instanceC, typeC) Dim result = FormatResult("b", value, New DkmClrType(CType(typeB, TypeImpl))) Dim children = GetChildren(result) Verify(children, EvalResult("P (A)", "1", "Integer", "DirectCast(b, A).P", DkmEvaluationResultFlags.ReadOnly), EvalResult("P (B)", "2", "Integer", "b.P", DkmEvaluationResultFlags.ReadOnly), EvalResult("P", "3", "Integer", "DirectCast(b, C).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithVirtualPropertiesAcrossDeclaredType() Dim source = " Class A Public Overridable Property P As Integer = 1 End Class Class B : Inherits A Public Overrides Property P As Integer = 2 End Class Class C : Inherits B End Class Class D : Inherits C Public Overrides Property p As Integer = 3 End Class" Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim typeD = assembly.GetType("D") Dim instanceD = Activator.CreateInstance(typeD) Dim value = CreateDkmClrValue(instanceD, typeD) Dim result = FormatResult("c", value, New DkmClrType(CType(typeC, TypeImpl))) Dim children = GetChildren(result) ' Ideally, we would only emit "c.P" for the full name of properties, but ' the added complexity of figuring that out (instead always just calling ' most derived) doesn't seem worth it. Verify(children, EvalResult("P", "3", "Integer", "DirectCast(c, D).P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A)", "0", "Integer", "DirectCast(c, A)._P"), EvalResult("_P", "0", "Integer", "c._P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_p", "3", "Integer", "DirectCast(c, D)._p", DkmEvaluationResultFlags.CanFavorite)) End Sub <WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")> <Fact> Public Sub RootVersusInternal() Const source = " Imports System.Diagnostics <DebuggerDisplay(""Value"", Name:=""Name"")> Class A End Class Class B Public A As A Public Sub New(a As A) Me.A = a End Sub End Class " Dim assembly = GetAssembly(source) Dim typeA = assembly.GetType("A") Dim typeB = assembly.GetType("B") Dim instanceA = typeA.Instantiate() Dim instanceB = typeB.Instantiate(instanceA) Dim result = FormatResult("a", CreateDkmClrValue(instanceA)) Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)) result = FormatResult("b", CreateDkmClrValue(instanceB)) Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.A", DkmEvaluationResultFlags.None)) 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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ExpansionTests : Inherits VisualBasicResultProviderTestBase <Fact> Public Sub Enums() Dim source = " Imports System Enum E A B End Enum Enum F As Byte A = 42 End Enum <Flags> Enum [if] [else] = 1 fi End Enum Class C Dim e As E = E.B Dim f As F = Nothing Dim g As [if] = [if].else Or [if].fi Dim h As [if] = 5 End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim rootExpr = "New C()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("e", "B {1}", "E", "(New C()).e", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.B"), EvalResult("f", "0", "F", "(New C()).f", DkmEvaluationResultFlags.CanFavorite, editableValue:="0"), EvalResult("g", "else Or fi {3}", "if", "(New C()).g", DkmEvaluationResultFlags.CanFavorite, editableValue:="[if].else Or [if].fi"), EvalResult("h", "5", "if", "(New C()).h", DkmEvaluationResultFlags.CanFavorite, editableValue:="5")) End Sub <Fact> Public Sub Nullable() Dim source = " Enum E A End Enum Structure S Friend Sub New(f as Integer) Me.F = f End Sub Dim F As Object End Structure Class C Dim e1 As E? = E.A Dim e2 As E? = Nothing Dim s1 As S? = New S(1) Dim s2 As S? = Nothing Dim o1 As Object = New System.Nullable(Of S)(Nothing) Dim o2 As Object = New System.Nullable(Of S)() End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim rootExpr = "New C()" Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("e1", "A {0}", "E?", "(New C()).e1", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.A"), EvalResult("e2", "Nothing", "E?", "(New C()).e2", DkmEvaluationResultFlags.CanFavorite), EvalResult("o1", "{S}", "Object {S}", "(New C()).o1", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("o2", "Nothing", "Object", "(New C()).o2", DkmEvaluationResultFlags.CanFavorite), EvalResult("s1", "{S}", "S?", "(New C()).s1", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("s2", "Nothing", "S?", "(New C()).s2", DkmEvaluationResultFlags.CanFavorite)) ' Dim o1 As Object = New System.Nullable(Of S)(Nothing) Verify(GetChildren(children(2)), EvalResult("F", "Nothing", "Object", "DirectCast((New C()).o1, S).F", DkmEvaluationResultFlags.CanFavorite)) ' Dim s1 As S? = New S(1) Verify(GetChildren(children(4)), EvalResult("F", "1", "Object {Integer}", "(New C()).s1.F", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub Pointers() Dim source = ".class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .field private int32* p .field private int32* q .method assembly hidebysig specialname rtspecialname instance void .ctor(native int p) cil managed { // Code size 21 (0x15) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call void* [mscorlib]System.IntPtr::op_Explicit(native int) IL_000f: stfld int32* C::p IL_0014: ret } }" Dim assembly = GetAssemblyFromIL(source) Dim type = assembly.GetType("C") Dim p = GCHandle.Alloc(4, GCHandleType.Pinned).AddrOfPinnedObject() Dim rootExpr = String.Format("new C({0})", p) Dim value = CreateDkmClrValue(ReflectionUtilities.Instantiate(type, p)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("p", PointerToString(p), "Integer*", String.Format("({0}).p", rootExpr), DkmEvaluationResultFlags.Expandable), EvalResult("q", PointerToString(IntPtr.Zero), "Integer*", String.Format("({0}).q", rootExpr))) Dim fullName = String.Format("*({0}).p", rootExpr) Verify(GetChildren(children(0)), EvalResult(fullName, "4", "Integer", fullName, DkmEvaluationResultFlags.None)) End Sub <Fact> Public Sub StaticMembers() Dim source = "Class A Const F As Integer = 1 Shared ReadOnly G As Integer = 2 End Class Class B : Inherits A End Class Structure S Const F As Object = Nothing Shared ReadOnly Property P As Object Get Return 3 End Get End Property End Structure Enum E A B End Enum Class C Dim a As A = Nothing Dim b As B = Nothing Dim s As New S() Dim sn? As S = Nothing Dim e As E = E.B End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim rootExpr = "New C()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("a", "Nothing", "A", "(New C()).a", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("b", "Nothing", "B", "(New C()).b", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("e", "B {1}", "E", "(New C()).e", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.B"), EvalResult("s", "{S}", "S", "(New C()).s", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("sn", "Nothing", "S?", "(New C()).sn", DkmEvaluationResultFlags.CanFavorite)) ' Dim a As A = Nothing Dim more = GetChildren(children(0)) Verify(more, EvalResult("Shared members", Nothing, "", "A", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) more = GetChildren(more(0)) Verify(more, EvalResult("F", "1", "Integer", "A.F", DkmEvaluationResultFlags.ReadOnly), EvalResult("G", "2", "Integer", "A.G", DkmEvaluationResultFlags.ReadOnly)) ' Dim s As New S() more = GetChildren(children(3)) Verify(more, EvalResult("Shared members", Nothing, "", "S", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) more = GetChildren(more(0)) Verify(more, EvalResult("F", "Nothing", "Object", "S.F", DkmEvaluationResultFlags.ReadOnly), EvalResult("P", "3", "Object {Integer}", "S.P", DkmEvaluationResultFlags.ReadOnly)) End Sub <Fact> Public Sub DeclaredTypeObject_Array() Dim source = " Interface I Property Q As Integer End Interface Class A Friend F As Object End Class Class B : Inherits A : Implements I Friend Sub New(f As Object) Me.F = f End Sub Friend ReadOnly Property P As Object Get Return Me.F End Get End Property Property Q As Integer Implements I.Q Get End Get Set End Set End Property End Class Class C Dim a() As A = { New B(1) } Dim b() As B = { New B(2) } Dim i() As I = { New B(3) } Dim o() As Object = { New B(4) } End Class " Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim children = GetChildren(FormatResult("c", CreateDkmClrValue(Activator.CreateInstance(typeC)))) Verify(children, EvalResult("a", "{Length=1}", "A()", "c.a", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("b", "{Length=1}", "B()", "c.b", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("i", "{Length=1}", "I()", "c.i", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite), EvalResult("o", "{Length=1}", "Object()", "c.o", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(0)).Single()), ' as A() EvalResult("F", "1", "Object {Integer}", "c.a(0).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "1", "Object {Integer}", "DirectCast(c.a(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.a(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(1)).Single()), ' as B() EvalResult("F", "2", "Object {Integer}", "c.b(0).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "2", "Object {Integer}", "c.b(0).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "c.b(0).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(2)).Single()), ' as I() EvalResult("F", "3", "Object {Integer}", "DirectCast(c.i(0), A).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "3", "Object {Integer}", "DirectCast(c.i(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.i(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) Verify(GetChildren(GetChildren(children(3)).Single()), ' as Object() EvalResult("F", "4", "Object {Integer}", "DirectCast(c.o(0), A).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "4", "Object {Integer}", "DirectCast(c.o(0), B).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Q", "0", "Integer", "DirectCast(c.o(0), B).Q", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub MultilineString() Dim str = vbCrLf & "line1" & vbCrLf & "line2" Dim quotedStr = "vbCrLf & ""line1"" & vbCrLf & ""line2""" Dim value = CreateDkmClrValue(str, evalFlags:=DkmEvaluationResultFlags.RawString) Dim result = FormatResult("str", value) Verify(result, EvalResult("str", quotedStr, "String", "str", DkmEvaluationResultFlags.RawString, editableValue:=quotedStr)) End Sub <Fact> Public Sub UnicodeChar() ' This Char is printable, so we expect the EditableValue to just be the Char. Dim c = ChrW(&H1234) Dim quotedChar = """" & c & """c" Dim value = CreateDkmClrValue(c) Dim result = FormatResult("c", value) Verify(result, EvalResult("c", quotedChar, "Char", "c", editableValue:=quotedChar)) ' This Char is not printable, so we expect the EditableValue to be the "ChrW" representation. quotedChar = "ChrW(&H7)" value = CreateDkmClrValue(ChrW(&H0007)) result = FormatResult("c", value, inspectionContext:=CreateDkmInspectionContext(radix:=16)) Verify(result, EvalResult("c", quotedChar, "Char", "c", editableValue:=quotedChar)) End Sub <Fact> Public Sub UnicodeString() Const quotedString = """" & ChrW(&H1234) & """ & ChrW(7)" Dim value = CreateDkmClrValue(New String({ChrW(&H1234), ChrW(&H0007)})) Dim result = FormatResult("s", value) Verify(result, EvalResult("s", quotedString, "String", "s", editableValue:=quotedString, flags:=DkmEvaluationResultFlags.RawString)) End Sub <Fact, WorkItem(1002381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1002381")> Public Sub BaseTypeEditableValue() Dim source = " Imports System Imports System.Collections.Generic <Flags> Enum E A = 1 B = 2 End Enum Class C Dim s1 As IEnumerable(Of Char) = String.Empty Dim d1 As Object = 1D Dim e1 As ValueType = E.A Or E.B End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult("o", value) Verify(result, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("d1", "1", "Object {Decimal}", "o.d1", DkmEvaluationResultFlags.CanFavorite, editableValue:="1D"), EvalResult("e1", "A Or B {3}", "System.ValueType {E}", "o.e1", DkmEvaluationResultFlags.CanFavorite, editableValue:="E.A Or E.B"), EvalResult("s1", """""", "System.Collections.Generic.IEnumerable(Of Char) {String}", "o.s1", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""""")) End Sub ''' <summary> ''' Hide members that have compiler-generated names. ''' </summary> ''' <remarks> ''' As in dev11, the FullName expressions don't parse. ''' </remarks> <Fact, WorkItem(1010498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010498")> Public Sub HiddenMembers() Dim source = ".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .field public object '@' .field public object '<' .field public static object '>' .field public static object '><' .field public object '<>' .field public object '1<>' .field public object '<2' .field public object '<>__' .field public object '<>k' .field public static object '<3>k' .field public static object '<<>>k' .field public static object '<>>k' .field public static object '<<>k' .field public static object '< >k' .field public object 'CS$' .field public object 'CS$<>0_' .field public object 'CS$<>7__8' .field public object 'CS$$<>7__8' .field public object 'CS<>7__8' .field public static object '$<>7__8' .field public static object 'CS$<M>7' } .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance object '<>k__get'() { ldnull ret } .method public static object '<M>7__get'() { ldnull ret } .property instance object '@'() { .get instance object B::'<>k__get'() } .property instance object '<'() { .get instance object B::'<>k__get'() } .property object '>'() { .get object B::'<M>7__get'() } .property object '><'() { .get object B::'<M>7__get'() } .property instance object '<>'() { .get instance object B::'<>k__get'() } .property instance object '1<>'() { .get instance object B::'<>k__get'() } .property instance object '<2'() { .get instance object B::'<>k__get'() } .property instance object '<>__'() { .get instance object B::'<>k__get'() } .property instance object '<>k'() { .get instance object B::'<>k__get'() } .property object '<3>k'() { .get object B::'<M>7__get'() } .property object '<<>>k'() { .get object B::'<M>7__get'() } .property object '<>>k'() { .get object B::'<M>7__get'() } .property object '<<>k'() { .get object B::'<M>7__get'() } .property object '< >k'() { .get object B::'<M>7__get'() } .property instance object 'VB$'() { .get instance object B::'<>k__get'() } .property instance object 'VB$<>0_'() { .get instance object B::'<>k__get'() } .property instance object 'VB$Me<>7__8'() { .get instance object B::'<>k__get'() } .property instance object 'VB$$<>7__8'() { .get instance object B::'<>k__get'() } .property instance object 'VB<>7__8'() { .get instance object B::'<>k__get'() } .property object '$<>7__8'() { .get object B::'<M>7__get'() } .property object 'CS$<M>7'() { .get object B::'<M>7__get'() } }" Dim assemblyBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing CommonTestBase.EmitILToArray(source, appendDefaultHeader:=True, includePdb:=False, assemblyBytes:=assemblyBytes, pdbBytes:=pdbBytes) Dim assembly = ReflectionUtilities.Load(assemblyBytes) Dim type = assembly.GetType("A") Dim rootExpr = "New A()" Dim value = CreateDkmClrValue(Activator.CreateInstance(type)) Dim result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{A}", "A", rootExpr, DkmEvaluationResultFlags.Expandable)) Dim children = GetChildren(result) Verify(children, EvalResult("1<>", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("@", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("CS<>7__8", "Nothing", "Object", fullName:=Nothing, DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "A", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) children = GetChildren(children(children.Length - 1)) Verify(children, EvalResult(">", "Nothing", "Object", fullName:=Nothing), EvalResult("><", "Nothing", "Object", fullName:=Nothing)) type = assembly.GetType("B") rootExpr = "New B()" value = CreateDkmClrValue(Activator.CreateInstance(type)) result = FormatResult(rootExpr, value) Verify(result, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable)) children = GetChildren(result) Verify(children, EvalResult("1<>", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("@", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("VB<>7__8", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "B", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) children = GetChildren(children(children.Length - 1)) Verify(children, EvalResult(">", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly), EvalResult("><", "Nothing", "Object", fullName:=Nothing, flags:=DkmEvaluationResultFlags.ReadOnly)) End Sub <Fact, WorkItem(965892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965892")> Public Sub DeclaredTypeAndRuntimeTypeDifferent() Dim source = " Class A End Class Class B : Inherits A End Class" Dim assembly = GetAssembly(source) Dim type = assembly.GetType("B") Dim declaredType = assembly.GetType("A") Dim value = CreateDkmClrValue(Activator.CreateInstance(type), type) Dim result = FormatResult("a", value, New DkmClrType(CType(declaredType, TypeImpl))) Verify(result, EvalResult("a", "{B}", "A {B}", "a", DkmEvaluationResultFlags.None)) Dim children = GetChildren(result) Verify(children) End Sub <Fact> Public Sub NameConflictsWithFieldOnBase() Dim source = " Class A Private f As Integer End Class Class B : Inherits A Friend f As Double End Class" Dim assembly = GetAssembly(source) Dim typeB = assembly.GetType("B") Dim instanceB = Activator.CreateInstance(typeB) Dim value = CreateDkmClrValue(instanceB, typeB) Dim result = FormatResult("b", value) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(b, A).f"), EvalResult("f", "0", "Double", "b.f", DkmEvaluationResultFlags.CanFavorite)) Dim typeA = assembly.GetType("A") value = CreateDkmClrValue(instanceB, typeB) result = FormatResult("a", value, New DkmClrType(CType(typeA, TypeImpl))) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "a.f"), EvalResult("f", "0", "Double", "DirectCast(a, B).f", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithFieldsOnMultipleBase() Dim source = " Class A Private f As Integer End Class Class B : Inherits A Friend f As Double End Class Class C : Inherits B End Class" Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(typeC) Dim value = CreateDkmClrValue(instanceC, typeC) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(c, A).f"), EvalResult("f", "0", "Double", "c.f", DkmEvaluationResultFlags.CanFavorite)) Dim typeB = assembly.GetType("B") value = CreateDkmClrValue(instanceC, typeC) result = FormatResult("b", value, New DkmClrType(CType(typeB, TypeImpl))) Verify(GetChildren(result), EvalResult("f (A)", "0", "Integer", "DirectCast(b, A).f"), EvalResult("f", "0", "Double", "b.f", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithPropertyOnNestedBase() Dim source = " Class A Private Property P As Integer Class B : Inherits A Friend Property P As Double End Class End Class Class C : Inherits A.B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("P (A)", "0", "Integer", "DirectCast(c, A).P"), EvalResult("P", "0", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A)", "0", "Integer", "DirectCast(c, A)._P"), EvalResult("_P", "0", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithPropertyOnGenericBase() Dim source = " Class A(Of T) Public Property P As T End Class Class B : Inherits A(Of Integer) Private Property P As Double End Class Class C : Inherits B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("P (A(Of Integer))", "0", "Integer", "DirectCast(c, A(Of Integer)).P"), EvalResult("P", "0", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A(Of Integer))", "0", "Integer", "DirectCast(c, A(Of Integer))._P"), EvalResult("_P", "0", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub PropertyNameConflictsWithFieldOnBase() Dim source = " Class A Public F As String End Class Class B : Inherits A Private Property F As Double End Class Class C : Inherits B End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Verify(GetChildren(result), EvalResult("F (A)", "Nothing", "String", "DirectCast(c, A).F"), EvalResult("F", "0", "Double", "c.F", DkmEvaluationResultFlags.CanFavorite), EvalResult("_F", "0", "Double", "c._F", DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithIndexerOnBase() Dim source = " Class A Public ReadOnly Property P(x As String) As String Get Return ""DeriveMe"" End Get End Property End Class Class B : Inherits A Public Property P As String = ""Derived"" End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("B") Dim instanceB = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceB, type) Dim result = FormatResult("b", value) Verify(GetChildren(result), EvalResult("P", """Derived""", "String", "b.P", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""Derived"""), EvalResult("_P", """Derived""", "String", "b._P", DkmEvaluationResultFlags.RawString Or DkmEvaluationResultFlags.CanFavorite, editableValue:="""Derived""")) End Sub <Fact> Public Sub NameConflictsWithPropertyHiddenByNameOnBase() Dim source = " Class A Shared S As Integer = 42 Friend Overridable Property p As Integer = 43 End Class Class B : Inherits A Friend Overrides Property P As Integer = 45 End Class Class C : Inherits B Shadows Property P As Double = 4.4 End Class " Dim assembly = GetAssembly(source) Dim type = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(type) Dim value = CreateDkmClrValue(instanceC, type) Dim result = FormatResult("c", value) Dim children = GetChildren(result) ' TODO: Name hiding across overrides should be case-insensitive in VB, ' so "p" in this case should be hidden by "P" (and we need to qualify "p" ' with the type name "B" To disambiguate). However, we also need to ' support multiple members on the same type that differ only by case ' (properties in C# that have the same name as their backing field, etc). Verify(children, EvalResult("P", "4.4", "Double", "c.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (B)", "45", "Integer", "DirectCast(c, B)._P"), EvalResult("_P", "4.4", "Double", "c._P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_p", "0", "Integer", "c._p", DkmEvaluationResultFlags.CanFavorite), EvalResult("p", "45", "Integer", "c.p", DkmEvaluationResultFlags.CanFavorite), EvalResult("Shared members", Nothing, "", "C", DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)) Verify(GetChildren(children(5)), EvalResult("S", "42", "Integer", "A.S")) End Sub <Fact, WorkItem(1074435, "DevDiv")> Public Sub NameConflictsWithInterfaceReimplementation() Dim source = " Interface I ReadOnly Property P As Integer End Interface Class A : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 1 End Get End Property End Class Class B : Inherits A : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 2 End Get End Property End Class Class C : Inherits B : Implements I Public ReadOnly Property P As Integer Implements I.P Get Return 3 End Get End Property End Class " Dim assembly = GetAssembly(source) Dim typeB = assembly.GetType("B") Dim typeC = assembly.GetType("C") Dim instanceC = Activator.CreateInstance(typeC) Dim value = CreateDkmClrValue(instanceC, typeC) Dim result = FormatResult("b", value, New DkmClrType(CType(typeB, TypeImpl))) Dim children = GetChildren(result) Verify(children, EvalResult("P (A)", "1", "Integer", "DirectCast(b, A).P", DkmEvaluationResultFlags.ReadOnly), EvalResult("P (B)", "2", "Integer", "b.P", DkmEvaluationResultFlags.ReadOnly), EvalResult("P", "3", "Integer", "DirectCast(b, C).P", DkmEvaluationResultFlags.ReadOnly Or DkmEvaluationResultFlags.CanFavorite)) End Sub <Fact> Public Sub NameConflictsWithVirtualPropertiesAcrossDeclaredType() Dim source = " Class A Public Overridable Property P As Integer = 1 End Class Class B : Inherits A Public Overrides Property P As Integer = 2 End Class Class C : Inherits B End Class Class D : Inherits C Public Overrides Property p As Integer = 3 End Class" Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim typeD = assembly.GetType("D") Dim instanceD = Activator.CreateInstance(typeD) Dim value = CreateDkmClrValue(instanceD, typeD) Dim result = FormatResult("c", value, New DkmClrType(CType(typeC, TypeImpl))) Dim children = GetChildren(result) ' Ideally, we would only emit "c.P" for the full name of properties, but ' the added complexity of figuring that out (instead always just calling ' most derived) doesn't seem worth it. Verify(children, EvalResult("P", "3", "Integer", "DirectCast(c, D).P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_P (A)", "0", "Integer", "DirectCast(c, A)._P"), EvalResult("_P", "0", "Integer", "c._P", DkmEvaluationResultFlags.CanFavorite), EvalResult("_p", "3", "Integer", "DirectCast(c, D)._p", DkmEvaluationResultFlags.CanFavorite)) End Sub <WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")> <Fact> Public Sub RootVersusInternal() Const source = " Imports System.Diagnostics <DebuggerDisplay(""Value"", Name:=""Name"")> Class A End Class Class B Public A As A Public Sub New(a As A) Me.A = a End Sub End Class " Dim assembly = GetAssembly(source) Dim typeA = assembly.GetType("A") Dim typeB = assembly.GetType("B") Dim instanceA = typeA.Instantiate() Dim instanceB = typeB.Instantiate(instanceA) Dim result = FormatResult("a", CreateDkmClrValue(instanceA)) Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)) result = FormatResult("b", CreateDkmClrValue(instanceB)) Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.A", DkmEvaluationResultFlags.None)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities #If CODE_STYLE Then Imports OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions #Else Imports Microsoft.CodeAnalysis.Options #End If Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports <ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicAddImportsService Inherits AbstractAddImportsService(Of CompilationUnitSyntax, NamespaceBlockSyntax, ImportsStatementSyntax, ImportsStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer()) Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean Dim importsA = TryCast(a, ImportsStatementSyntax) Dim importsB = TryCast(b, ImportsStatementSyntax) If importsA Is Nothing OrElse importsB Is Nothing Then Return False End If Return ImportsStatementComparer.Compare(importsA, importsB) = 0 End Function Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode) Dim result = ArrayBuilder(Of SyntaxNode).GetInstance() For Each import In compilation.MemberImports() If TypeOf import Is INamespaceSymbol Then result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString())) End If Next Return result.ToImmutableAndFree() End Function Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax). Where(Function(c) c.Alias IsNot Nothing). FirstOrDefault()?.Alias End Function Protected Overrides Function PlaceImportsInsideNamespaces(options As OptionSet) As Boolean ' Visual Basic doesn't support imports inside namespaces Return False End Function Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean ' Visual Basic doesn't support static imports Return False End Function Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) If node.Kind() = SyntaxKind.CompilationUnit Then Return DirectCast(node, CompilationUnitSyntax).Imports End If Return Nothing End Function Protected Overrides Function Rewrite( externAliases() As ImportsStatementSyntax, usingDirectives() As ImportsStatementSyntax, staticUsingDirectives() As ImportsStatementSyntax, aliasDirectives() As ImportsStatementSyntax, externContainer As SyntaxNode, usingContainer As SyntaxNode, staticUsingContainer As SyntaxNode, aliasContainer As SyntaxNode, placeSystemNamespaceFirst As Boolean, allowInHiddenRegions As Boolean, root As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode Dim compilationUnit = DirectCast(root, CompilationUnitSyntax) If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then Return compilationUnit End If Return compilationUnit.AddImportsStatements( usingDirectives.Concat(aliasDirectives).ToList(), placeSystemNamespaceFirst, Array.Empty(Of SyntaxAnnotation)) End Function Private Class CaseInsensitiveTokenComparer Implements IComparer(Of SyntaxToken) Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. ' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens. Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText()) 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities #If CODE_STYLE Then Imports OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions #Else Imports Microsoft.CodeAnalysis.Options #End If Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports <ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicAddImportsService Inherits AbstractAddImportsService(Of CompilationUnitSyntax, NamespaceBlockSyntax, ImportsStatementSyntax, ImportsStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer()) Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean Dim importsA = TryCast(a, ImportsStatementSyntax) Dim importsB = TryCast(b, ImportsStatementSyntax) If importsA Is Nothing OrElse importsB Is Nothing Then Return False End If Return ImportsStatementComparer.Compare(importsA, importsB) = 0 End Function Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode) Dim result = ArrayBuilder(Of SyntaxNode).GetInstance() For Each import In compilation.MemberImports() If TypeOf import Is INamespaceSymbol Then result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString())) End If Next Return result.ToImmutableAndFree() End Function Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax). Where(Function(c) c.Alias IsNot Nothing). FirstOrDefault()?.Alias End Function Protected Overrides Function PlaceImportsInsideNamespaces(options As OptionSet) As Boolean ' Visual Basic doesn't support imports inside namespaces Return False End Function Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean ' Visual Basic doesn't support static imports Return False End Function Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax) If node.Kind() = SyntaxKind.CompilationUnit Then Return DirectCast(node, CompilationUnitSyntax).Imports End If Return Nothing End Function Protected Overrides Function Rewrite( externAliases() As ImportsStatementSyntax, usingDirectives() As ImportsStatementSyntax, staticUsingDirectives() As ImportsStatementSyntax, aliasDirectives() As ImportsStatementSyntax, externContainer As SyntaxNode, usingContainer As SyntaxNode, staticUsingContainer As SyntaxNode, aliasContainer As SyntaxNode, placeSystemNamespaceFirst As Boolean, allowInHiddenRegions As Boolean, root As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode Dim compilationUnit = DirectCast(root, CompilationUnitSyntax) If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then Return compilationUnit End If Return compilationUnit.AddImportsStatements( usingDirectives.Concat(aliasDirectives).ToList(), placeSystemNamespaceFirst, Array.Empty(Of SyntaxAnnotation)) End Function Private Class CaseInsensitiveTokenComparer Implements IComparer(Of SyntaxToken) Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. ' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens. Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText()) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Test/Resources/Core/SymbolsTests/RetargetingCycle/V2/ClassB.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. ' vbc ClassB.vb /target:library /vbruntime- Public Class ClassB End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. ' vbc ClassB.vb /target:library /vbruntime- Public Class ClassB End Class
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InlineDeclaration), Shared] internal partial class CSharpInlineDeclarationCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInlineDeclarationCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InlineDeclarationDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif // Gather all statements to be removed // We need this to find the statements we can safely attach trivia to var declarationsToRemove = new HashSet<StatementSyntax>(); foreach (var diagnostic in diagnostics) { declarationsToRemove.Add((LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken).Parent.Parent); } // Attempt to use an out-var declaration if that's the style the user prefers. // Note: if using 'var' would cause a problem, we will use the actual type // of the local. This is necessary in some cases (for example, when the // type of the out-var-decl affects overload resolution or generic instantiation). var originalRoot = editor.OriginalRoot; var originalNodes = diagnostics.SelectAsArray(diagnostic => FindDiagnosticNodes(diagnostic, cancellationToken)); await editor.ApplyExpressionLevelSemanticEditsAsync( document, originalNodes, t => { using var additionalNodesToTrackDisposer = ArrayBuilder<SyntaxNode>.GetInstance(capacity: 2, out var additionalNodesToTrack); additionalNodesToTrack.Add(t.identifier); additionalNodesToTrack.Add(t.declarator); return (t.invocationOrCreation, additionalNodesToTrack.ToImmutable()); }, (_1, _2, _3) => true, (semanticModel, currentRoot, t, currentNode) => ReplaceIdentifierWithInlineDeclaration( options, semanticModel, currentRoot, t.declarator, t.identifier, currentNode, declarationsToRemove, document.Project.Solution.Workspace, cancellationToken), cancellationToken).ConfigureAwait(false); } private static (VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode invocationOrCreation) FindDiagnosticNodes( Diagnostic diagnostic, CancellationToken cancellationToken) { // Recover the nodes we care about. var declaratorLocation = diagnostic.AdditionalLocations[0]; var identifierLocation = diagnostic.AdditionalLocations[1]; var invocationOrCreationLocation = diagnostic.AdditionalLocations[2]; var declarator = (VariableDeclaratorSyntax)declaratorLocation.FindNode(cancellationToken); var identifier = (IdentifierNameSyntax)identifierLocation.FindNode(cancellationToken); var invocationOrCreation = (ExpressionSyntax)invocationOrCreationLocation.FindNode( getInnermostNodeForTie: true, cancellationToken: cancellationToken); return (declarator, identifier, invocationOrCreation); } private static SyntaxNode ReplaceIdentifierWithInlineDeclaration( OptionSet options, SemanticModel semanticModel, SyntaxNode currentRoot, VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode currentNode, HashSet<StatementSyntax> declarationsToRemove, Workspace workspace, CancellationToken cancellationToken) { declarator = currentRoot.GetCurrentNode(declarator); identifier = currentRoot.GetCurrentNode(identifier); var editor = new SyntaxEditor(currentRoot, workspace); var sourceText = currentRoot.GetText(); var declaration = (VariableDeclarationSyntax)declarator.Parent; var singleDeclarator = declaration.Variables.Count == 1; if (singleDeclarator) { // This was a local statement with a single variable in it. Just Remove // the entire local declaration statement. Note that comments belonging to // this local statement will be moved to be above the statement containing // the out-var. var localDeclarationStatement = (LocalDeclarationStatementSyntax)declaration.Parent; var block = (BlockSyntax)localDeclarationStatement.Parent; var declarationIndex = block.Statements.IndexOf(localDeclarationStatement); // Try to find a predecessor Statement on the same line that isn't going to be removed StatementSyntax priorStatementSyntax = null; var localDeclarationToken = localDeclarationStatement.GetFirstToken(); for (var i = declarationIndex - 1; i >= 0; i--) { var statementSyntax = block.Statements[i]; if (declarationsToRemove.Contains(statementSyntax)) { continue; } if (sourceText.AreOnSameLine(statementSyntax.GetLastToken(), localDeclarationToken)) { priorStatementSyntax = statementSyntax; } break; } if (priorStatementSyntax != null) { // There's another statement on the same line as this declaration statement. // i.e. int a; int b; // // Just move all trivia from our statement to be trailing trivia of the previous // statement editor.ReplaceNode( priorStatementSyntax, (s, g) => s.WithAppendedTrailingTrivia(localDeclarationStatement.GetTrailingTrivia())); } else { // Trivia on the local declaration will move to the next statement. // use the callback form as the next statement may be the place where we're // inlining the declaration, and thus need to see the effects of that change. // Find the next Statement that isn't going to be removed. // We initialize this to null here but we must see at least the statement // into which the declaration is going to be inlined so this will be not null StatementSyntax nextStatementSyntax = null; for (var i = declarationIndex + 1; i < block.Statements.Count; i++) { var statement = block.Statements[i]; if (!declarationsToRemove.Contains(statement)) { nextStatementSyntax = statement; break; } } editor.ReplaceNode( nextStatementSyntax, (s, g) => s.WithPrependedNonIndentationTriviaFrom(localDeclarationStatement)); } editor.RemoveNode(localDeclarationStatement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } else { // Otherwise, just remove the single declarator. Note: we'll move the comments // 'on' the declarator to the out-var location. This is a little bit trickier // than normal due to how our comment-association rules work. i.e. if you have: // // var /*c1*/ i /*c2*/, /*c3*/ j /*c4*/; // // In this case 'c1' is owned by the 'var' token, not 'i', and 'c3' is owned by // the comment token not 'j'. editor.RemoveNode(declarator); if (declarator == declaration.Variables[0]) { // If we're removing the first declarator, and it's on the same line // as the previous token, then we want to remove all the trivia belonging // to the previous token. We're going to move it along with this declarator. // If we don't, then the comment will stay with the previous token. // // Note that the moving of the comment happens later on when we make the // declaration expression. if (sourceText.AreOnSameLine(declarator.GetFirstToken(), declarator.GetFirstToken().GetPreviousToken(includeSkipped: true))) { editor.ReplaceNode( declaration.Type, (t, g) => t.WithTrailingTrivia(SyntaxFactory.ElasticSpace).WithoutAnnotations(Formatter.Annotation)); } } } // get the type that we want to put in the out-var-decl based on the user's options. // i.e. prefer 'out var' if that is what the user wants. Note: if we have: // // Method(out var x) // // Then the type is not-apparent, and we should not use var if the user only wants // it for apparent types var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken); var newType = GenerateTypeSyntaxOrVar(local.Type, options); var declarationExpression = GetDeclarationExpression( sourceText, identifier, newType, singleDeclarator ? null : declarator); // Check if using out-var changed problem semantics. var semanticsChanged = SemanticsChanged(semanticModel, currentNode, identifier, declarationExpression, cancellationToken); if (semanticsChanged) { // Switching to 'var' changed semantics. Just use the original type of the local. // If the user originally wrote it something other than 'var', then use what they // wrote. Otherwise, synthesize the actual type of the local. var explicitType = declaration.Type.IsVar ? local.Type?.GenerateTypeSyntax() : declaration.Type; declarationExpression = SyntaxFactory.DeclarationExpression(explicitType, declarationExpression.Designation); } editor.ReplaceNode(identifier, declarationExpression); return editor.GetChangedRoot(); } public static TypeSyntax GenerateTypeSyntaxOrVar( ITypeSymbol symbol, OptionSet options) { var useVar = IsVarDesired(symbol, options); // Note: we cannot use ".GenerateTypeSyntax()" only here. that's because we're // actually creating a DeclarationExpression and currently the Simplifier cannot // analyze those due to limitations between how it uses Speculative SemanticModels // and how those don't handle new declarations well. return useVar ? SyntaxFactory.IdentifierName("var") : symbol.GenerateTypeSyntax(); } private static bool IsVarDesired(ITypeSymbol type, OptionSet options) { // If they want it for intrinsics, and this is an intrinsic, then use var. if (type.IsSpecialType() == true) { return options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value; } // If they want "var" whenever possible, then use "var". return options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value; } private static DeclarationExpressionSyntax GetDeclarationExpression( SourceText sourceText, IdentifierNameSyntax identifier, TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt) { var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier); if (declaratorOpt != null) { // We're removing a single declarator. Copy any comments it has to the out-var. // // Note: this is tricky due to comment ownership. We want the comments that logically // belong to the declarator, even if our syntax model attaches them to other tokens. var precedingTrivia = declaratorOpt.GetAllPrecedingTriviaToPreviousToken( sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine: true); if (precedingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { designation = designation.WithPrependedLeadingTrivia(MassageTrivia(precedingTrivia)); } if (declaratorOpt.GetTrailingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { designation = designation.WithAppendedTrailingTrivia(MassageTrivia(declaratorOpt.GetTrailingTrivia())); } } newType = newType.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation); // We need trivia between the type declaration and designation or this will generate // "out inti", but we might have trivia in the form of comments etc from the original // designation and in those cases adding elastic trivia will break formatting. if (!designation.HasLeadingTrivia) { newType = newType.WithAppendedTrailingTrivia(SyntaxFactory.ElasticSpace); } return SyntaxFactory.DeclarationExpression(newType, designation); } private static IEnumerable<SyntaxTrivia> MassageTrivia(IEnumerable<SyntaxTrivia> triviaList) { foreach (var trivia in triviaList) { if (trivia.IsSingleOrMultiLineComment()) { yield return trivia; } else if (trivia.IsWhitespace()) { // Condense whitespace down to single spaces. We don't want things like // indentation spaces to be inserted in the out-var location. It is appropriate // though to have single spaces to help separate out things like comments and // tokens though. yield return SyntaxFactory.Space; } } } private static bool SemanticsChanged( SemanticModel semanticModel, SyntaxNode nodeToReplace, IdentifierNameSyntax identifier, DeclarationExpressionSyntax declarationExpression, CancellationToken cancellationToken) { if (declarationExpression.Type.IsVar) { // Options want us to use 'var' if we can. Make sure we didn't change // the semantics of the call by doing this. // Find the symbol that the existing invocation points to. var previousSymbol = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken).Symbol; // Now, create a speculative model in which we make the change. Make sure // we still point to the same symbol afterwards. var topmostContainer = GetTopmostContainer(nodeToReplace); if (topmostContainer == null) { // Couldn't figure out what we were contained in. Have to assume that semantics // Are changing. return true; } var annotation = new SyntaxAnnotation(); var updatedTopmostContainer = topmostContainer.ReplaceNode( nodeToReplace, nodeToReplace.ReplaceNode(identifier, declarationExpression) .WithAdditionalAnnotations(annotation)); if (!TryGetSpeculativeSemanticModel(semanticModel, topmostContainer.SpanStart, updatedTopmostContainer, out var speculativeModel)) { // Couldn't figure out the new semantics. Assume semantics changed. return true; } var updatedInvocationOrCreation = updatedTopmostContainer.GetAnnotatedNodes(annotation).Single(); var updatedSymbolInfo = speculativeModel.GetSymbolInfo(updatedInvocationOrCreation, cancellationToken); if (!SymbolEquivalenceComparer.Instance.Equals(previousSymbol, updatedSymbolInfo.Symbol)) { // We're pointing at a new symbol now. Semantic have changed. return true; } } return false; } private static SyntaxNode GetTopmostContainer(SyntaxNode expression) { return expression.GetAncestorsOrThis( a => a is StatementSyntax || a is EqualsValueClauseSyntax || a is ArrowExpressionClauseSyntax || a is ConstructorInitializerSyntax).LastOrDefault(); } private static bool TryGetSpeculativeSemanticModel( SemanticModel semanticModel, int position, SyntaxNode topmostContainer, out SemanticModel speculativeModel) { switch (topmostContainer) { case StatementSyntax statement: return semanticModel.TryGetSpeculativeSemanticModel(position, statement, out speculativeModel); case EqualsValueClauseSyntax equalsValue: return semanticModel.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel); case ArrowExpressionClauseSyntax arrowExpression: return semanticModel.TryGetSpeculativeSemanticModel(position, arrowExpression, out speculativeModel); case ConstructorInitializerSyntax constructorInitializer: return semanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel); } speculativeModel = null; return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Inline_variable_declaration, createChangedDocument, CSharpAnalyzersResources.Inline_variable_declaration) { } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InlineDeclaration), Shared] internal partial class CSharpInlineDeclarationCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInlineDeclarationCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InlineDeclarationDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif // Gather all statements to be removed // We need this to find the statements we can safely attach trivia to var declarationsToRemove = new HashSet<StatementSyntax>(); foreach (var diagnostic in diagnostics) { declarationsToRemove.Add((LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken).Parent.Parent); } // Attempt to use an out-var declaration if that's the style the user prefers. // Note: if using 'var' would cause a problem, we will use the actual type // of the local. This is necessary in some cases (for example, when the // type of the out-var-decl affects overload resolution or generic instantiation). var originalRoot = editor.OriginalRoot; var originalNodes = diagnostics.SelectAsArray(diagnostic => FindDiagnosticNodes(diagnostic, cancellationToken)); await editor.ApplyExpressionLevelSemanticEditsAsync( document, originalNodes, t => { using var additionalNodesToTrackDisposer = ArrayBuilder<SyntaxNode>.GetInstance(capacity: 2, out var additionalNodesToTrack); additionalNodesToTrack.Add(t.identifier); additionalNodesToTrack.Add(t.declarator); return (t.invocationOrCreation, additionalNodesToTrack.ToImmutable()); }, (_1, _2, _3) => true, (semanticModel, currentRoot, t, currentNode) => ReplaceIdentifierWithInlineDeclaration( options, semanticModel, currentRoot, t.declarator, t.identifier, currentNode, declarationsToRemove, document.Project.Solution.Workspace, cancellationToken), cancellationToken).ConfigureAwait(false); } private static (VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode invocationOrCreation) FindDiagnosticNodes( Diagnostic diagnostic, CancellationToken cancellationToken) { // Recover the nodes we care about. var declaratorLocation = diagnostic.AdditionalLocations[0]; var identifierLocation = diagnostic.AdditionalLocations[1]; var invocationOrCreationLocation = diagnostic.AdditionalLocations[2]; var declarator = (VariableDeclaratorSyntax)declaratorLocation.FindNode(cancellationToken); var identifier = (IdentifierNameSyntax)identifierLocation.FindNode(cancellationToken); var invocationOrCreation = (ExpressionSyntax)invocationOrCreationLocation.FindNode( getInnermostNodeForTie: true, cancellationToken: cancellationToken); return (declarator, identifier, invocationOrCreation); } private static SyntaxNode ReplaceIdentifierWithInlineDeclaration( OptionSet options, SemanticModel semanticModel, SyntaxNode currentRoot, VariableDeclaratorSyntax declarator, IdentifierNameSyntax identifier, SyntaxNode currentNode, HashSet<StatementSyntax> declarationsToRemove, Workspace workspace, CancellationToken cancellationToken) { declarator = currentRoot.GetCurrentNode(declarator); identifier = currentRoot.GetCurrentNode(identifier); var editor = new SyntaxEditor(currentRoot, workspace); var sourceText = currentRoot.GetText(); var declaration = (VariableDeclarationSyntax)declarator.Parent; var singleDeclarator = declaration.Variables.Count == 1; if (singleDeclarator) { // This was a local statement with a single variable in it. Just Remove // the entire local declaration statement. Note that comments belonging to // this local statement will be moved to be above the statement containing // the out-var. var localDeclarationStatement = (LocalDeclarationStatementSyntax)declaration.Parent; var block = (BlockSyntax)localDeclarationStatement.Parent; var declarationIndex = block.Statements.IndexOf(localDeclarationStatement); // Try to find a predecessor Statement on the same line that isn't going to be removed StatementSyntax priorStatementSyntax = null; var localDeclarationToken = localDeclarationStatement.GetFirstToken(); for (var i = declarationIndex - 1; i >= 0; i--) { var statementSyntax = block.Statements[i]; if (declarationsToRemove.Contains(statementSyntax)) { continue; } if (sourceText.AreOnSameLine(statementSyntax.GetLastToken(), localDeclarationToken)) { priorStatementSyntax = statementSyntax; } break; } if (priorStatementSyntax != null) { // There's another statement on the same line as this declaration statement. // i.e. int a; int b; // // Just move all trivia from our statement to be trailing trivia of the previous // statement editor.ReplaceNode( priorStatementSyntax, (s, g) => s.WithAppendedTrailingTrivia(localDeclarationStatement.GetTrailingTrivia())); } else { // Trivia on the local declaration will move to the next statement. // use the callback form as the next statement may be the place where we're // inlining the declaration, and thus need to see the effects of that change. // Find the next Statement that isn't going to be removed. // We initialize this to null here but we must see at least the statement // into which the declaration is going to be inlined so this will be not null StatementSyntax nextStatementSyntax = null; for (var i = declarationIndex + 1; i < block.Statements.Count; i++) { var statement = block.Statements[i]; if (!declarationsToRemove.Contains(statement)) { nextStatementSyntax = statement; break; } } editor.ReplaceNode( nextStatementSyntax, (s, g) => s.WithPrependedNonIndentationTriviaFrom(localDeclarationStatement)); } editor.RemoveNode(localDeclarationStatement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } else { // Otherwise, just remove the single declarator. Note: we'll move the comments // 'on' the declarator to the out-var location. This is a little bit trickier // than normal due to how our comment-association rules work. i.e. if you have: // // var /*c1*/ i /*c2*/, /*c3*/ j /*c4*/; // // In this case 'c1' is owned by the 'var' token, not 'i', and 'c3' is owned by // the comment token not 'j'. editor.RemoveNode(declarator); if (declarator == declaration.Variables[0]) { // If we're removing the first declarator, and it's on the same line // as the previous token, then we want to remove all the trivia belonging // to the previous token. We're going to move it along with this declarator. // If we don't, then the comment will stay with the previous token. // // Note that the moving of the comment happens later on when we make the // declaration expression. if (sourceText.AreOnSameLine(declarator.GetFirstToken(), declarator.GetFirstToken().GetPreviousToken(includeSkipped: true))) { editor.ReplaceNode( declaration.Type, (t, g) => t.WithTrailingTrivia(SyntaxFactory.ElasticSpace).WithoutAnnotations(Formatter.Annotation)); } } } // get the type that we want to put in the out-var-decl based on the user's options. // i.e. prefer 'out var' if that is what the user wants. Note: if we have: // // Method(out var x) // // Then the type is not-apparent, and we should not use var if the user only wants // it for apparent types var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken); var newType = GenerateTypeSyntaxOrVar(local.Type, options); var declarationExpression = GetDeclarationExpression( sourceText, identifier, newType, singleDeclarator ? null : declarator); // Check if using out-var changed problem semantics. var semanticsChanged = SemanticsChanged(semanticModel, currentNode, identifier, declarationExpression, cancellationToken); if (semanticsChanged) { // Switching to 'var' changed semantics. Just use the original type of the local. // If the user originally wrote it something other than 'var', then use what they // wrote. Otherwise, synthesize the actual type of the local. var explicitType = declaration.Type.IsVar ? local.Type?.GenerateTypeSyntax() : declaration.Type; declarationExpression = SyntaxFactory.DeclarationExpression(explicitType, declarationExpression.Designation); } editor.ReplaceNode(identifier, declarationExpression); return editor.GetChangedRoot(); } public static TypeSyntax GenerateTypeSyntaxOrVar( ITypeSymbol symbol, OptionSet options) { var useVar = IsVarDesired(symbol, options); // Note: we cannot use ".GenerateTypeSyntax()" only here. that's because we're // actually creating a DeclarationExpression and currently the Simplifier cannot // analyze those due to limitations between how it uses Speculative SemanticModels // and how those don't handle new declarations well. return useVar ? SyntaxFactory.IdentifierName("var") : symbol.GenerateTypeSyntax(); } private static bool IsVarDesired(ITypeSymbol type, OptionSet options) { // If they want it for intrinsics, and this is an intrinsic, then use var. if (type.IsSpecialType() == true) { return options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value; } // If they want "var" whenever possible, then use "var". return options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value; } private static DeclarationExpressionSyntax GetDeclarationExpression( SourceText sourceText, IdentifierNameSyntax identifier, TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt) { var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier); if (declaratorOpt != null) { // We're removing a single declarator. Copy any comments it has to the out-var. // // Note: this is tricky due to comment ownership. We want the comments that logically // belong to the declarator, even if our syntax model attaches them to other tokens. var precedingTrivia = declaratorOpt.GetAllPrecedingTriviaToPreviousToken( sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine: true); if (precedingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { designation = designation.WithPrependedLeadingTrivia(MassageTrivia(precedingTrivia)); } if (declaratorOpt.GetTrailingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { designation = designation.WithAppendedTrailingTrivia(MassageTrivia(declaratorOpt.GetTrailingTrivia())); } } newType = newType.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation); // We need trivia between the type declaration and designation or this will generate // "out inti", but we might have trivia in the form of comments etc from the original // designation and in those cases adding elastic trivia will break formatting. if (!designation.HasLeadingTrivia) { newType = newType.WithAppendedTrailingTrivia(SyntaxFactory.ElasticSpace); } return SyntaxFactory.DeclarationExpression(newType, designation); } private static IEnumerable<SyntaxTrivia> MassageTrivia(IEnumerable<SyntaxTrivia> triviaList) { foreach (var trivia in triviaList) { if (trivia.IsSingleOrMultiLineComment()) { yield return trivia; } else if (trivia.IsWhitespace()) { // Condense whitespace down to single spaces. We don't want things like // indentation spaces to be inserted in the out-var location. It is appropriate // though to have single spaces to help separate out things like comments and // tokens though. yield return SyntaxFactory.Space; } } } private static bool SemanticsChanged( SemanticModel semanticModel, SyntaxNode nodeToReplace, IdentifierNameSyntax identifier, DeclarationExpressionSyntax declarationExpression, CancellationToken cancellationToken) { if (declarationExpression.Type.IsVar) { // Options want us to use 'var' if we can. Make sure we didn't change // the semantics of the call by doing this. // Find the symbol that the existing invocation points to. var previousSymbol = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken).Symbol; // Now, create a speculative model in which we make the change. Make sure // we still point to the same symbol afterwards. var topmostContainer = GetTopmostContainer(nodeToReplace); if (topmostContainer == null) { // Couldn't figure out what we were contained in. Have to assume that semantics // Are changing. return true; } var annotation = new SyntaxAnnotation(); var updatedTopmostContainer = topmostContainer.ReplaceNode( nodeToReplace, nodeToReplace.ReplaceNode(identifier, declarationExpression) .WithAdditionalAnnotations(annotation)); if (!TryGetSpeculativeSemanticModel(semanticModel, topmostContainer.SpanStart, updatedTopmostContainer, out var speculativeModel)) { // Couldn't figure out the new semantics. Assume semantics changed. return true; } var updatedInvocationOrCreation = updatedTopmostContainer.GetAnnotatedNodes(annotation).Single(); var updatedSymbolInfo = speculativeModel.GetSymbolInfo(updatedInvocationOrCreation, cancellationToken); if (!SymbolEquivalenceComparer.Instance.Equals(previousSymbol, updatedSymbolInfo.Symbol)) { // We're pointing at a new symbol now. Semantic have changed. return true; } } return false; } private static SyntaxNode GetTopmostContainer(SyntaxNode expression) { return expression.GetAncestorsOrThis( a => a is StatementSyntax || a is EqualsValueClauseSyntax || a is ArrowExpressionClauseSyntax || a is ConstructorInitializerSyntax).LastOrDefault(); } private static bool TryGetSpeculativeSemanticModel( SemanticModel semanticModel, int position, SyntaxNode topmostContainer, out SemanticModel speculativeModel) { switch (topmostContainer) { case StatementSyntax statement: return semanticModel.TryGetSpeculativeSemanticModel(position, statement, out speculativeModel); case EqualsValueClauseSyntax equalsValue: return semanticModel.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel); case ArrowExpressionClauseSyntax arrowExpression: return semanticModel.TryGetSpeculativeSemanticModel(position, arrowExpression, out speculativeModel); case ConstructorInitializerSyntax constructorInitializer: return semanticModel.TryGetSpeculativeSemanticModel(position, constructorInitializer, out speculativeModel); } speculativeModel = null; return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Inline_variable_declaration, createChangedDocument, CSharpAnalyzersResources.Inline_variable_declaration) { } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Test/TextEditor/OpenDocumentTests.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor { [UseExportProvider] public class OpenDocumentTests { [WpfFact, Trait(Traits.Feature, Traits.Features.Workspace)] public void LinkedFiles() { // We want to assert that if the open document is linked into multiple projects, we // update all documents at the same time with the changed text. Otherwise things will get // out of sync. var hostServices = EditorTestCompositions.EditorFeatures.GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var textBufferFactoryService = ((IMefHostExportProvider)hostServices).GetExports<ITextBufferFactoryService>().Single().Value; var buffer = textBufferFactoryService.CreateTextBuffer("Hello", textBufferFactoryService.TextContentType); var sourceTextContainer = buffer.AsTextContainer(); // We're going to add two projects that both consume the same file const string FilePath = "Z:\\Foo.cs"; var documentIds = new List<DocumentId>(); for (var i = 0; i < 2; i++) { var projectId = workspace.AddProject($"Project{i}", LanguageNames.CSharp).Id; var documentId = DocumentId.CreateNewId(projectId); workspace.AddDocument(DocumentInfo.Create(documentId, "Foo.cs", filePath: FilePath)); workspace.OnDocumentOpened(documentId, sourceTextContainer); documentIds.Add(documentId); } // Confirm the files have been linked by file path. This isn't the core part of this test but without it // nothing else will work. Assert.Equal(documentIds, workspace.CurrentSolution.GetDocumentIdsWithFilePath(FilePath)); Assert.Equal(new[] { documentIds.Last() }, workspace.CurrentSolution.GetDocument(documentIds.First()).GetLinkedDocumentIds()); // Now the core test: first, if we make a modified version of the source text, and attempt to get the document for it, // both copies should be updated. var originalSnapshot = buffer.CurrentSnapshot; buffer.Insert(5, ", World!"); var newDocumentWithChanges = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); // Since we're calling this on the current snapshot and we observed the text edit synchronously, // no forking actually should have happened. Assert.Same(workspace.CurrentSolution, newDocumentWithChanges.Project.Solution); Assert.Equal("Hello, World!", newDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal("Hello, World!", newDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString()); // Now let's fetch back for the original snapshot. Both linked copies should be updated. var originalDocumentWithChanges = originalSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Assert.NotSame(workspace.CurrentSolution, originalDocumentWithChanges.Project.Solution); Assert.Equal("Hello", originalDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal("Hello", originalDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).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 System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor { [UseExportProvider] public class OpenDocumentTests { [WpfFact, Trait(Traits.Feature, Traits.Features.Workspace)] public void LinkedFiles() { // We want to assert that if the open document is linked into multiple projects, we // update all documents at the same time with the changed text. Otherwise things will get // out of sync. var hostServices = EditorTestCompositions.EditorFeatures.GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var textBufferFactoryService = ((IMefHostExportProvider)hostServices).GetExports<ITextBufferFactoryService>().Single().Value; var buffer = textBufferFactoryService.CreateTextBuffer("Hello", textBufferFactoryService.TextContentType); var sourceTextContainer = buffer.AsTextContainer(); // We're going to add two projects that both consume the same file const string FilePath = "Z:\\Foo.cs"; var documentIds = new List<DocumentId>(); for (var i = 0; i < 2; i++) { var projectId = workspace.AddProject($"Project{i}", LanguageNames.CSharp).Id; var documentId = DocumentId.CreateNewId(projectId); workspace.AddDocument(DocumentInfo.Create(documentId, "Foo.cs", filePath: FilePath)); workspace.OnDocumentOpened(documentId, sourceTextContainer); documentIds.Add(documentId); } // Confirm the files have been linked by file path. This isn't the core part of this test but without it // nothing else will work. Assert.Equal(documentIds, workspace.CurrentSolution.GetDocumentIdsWithFilePath(FilePath)); Assert.Equal(new[] { documentIds.Last() }, workspace.CurrentSolution.GetDocument(documentIds.First()).GetLinkedDocumentIds()); // Now the core test: first, if we make a modified version of the source text, and attempt to get the document for it, // both copies should be updated. var originalSnapshot = buffer.CurrentSnapshot; buffer.Insert(5, ", World!"); var newDocumentWithChanges = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); // Since we're calling this on the current snapshot and we observed the text edit synchronously, // no forking actually should have happened. Assert.Same(workspace.CurrentSolution, newDocumentWithChanges.Project.Solution); Assert.Equal("Hello, World!", newDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal("Hello, World!", newDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString()); // Now let's fetch back for the original snapshot. Both linked copies should be updated. var originalDocumentWithChanges = originalSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Assert.NotSame(workspace.CurrentSolution, originalDocumentWithChanges.Project.Solution); Assert.Equal("Hello", originalDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString()); Assert.Equal("Hello", originalDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString()); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/EventCollectorTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class EventCollectorTests Inherits AbstractEventCollectorTests #Region "Imports statements" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Imports System </Code> Await TestAsync(code, changedCode, Add("System")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add2() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add3() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add4() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add5() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq, System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add6() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System, System.Linq Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add7() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System, S = System.Linq Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("System", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove2() As Task Dim code = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove3() As Task Dim code = <Code> Imports System Imports System.Linq Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove4() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports System.Linq </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove5() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports System.Linq Class C End Class </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic End Class </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing), Remove("C", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove6() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports &lt;xmlns:aw="http://www.adventure-works.com"&gt; Class C End Class </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic Class C End Class </Code> ' Note: XML namespaces aren't supported by VB code model, so there should be no events when they're removed. Await TestAsync(code, changedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Rename1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> Imports System.Linq </Code> Await TestAsync(code, changedCode, Rename("System.Linq")) End Function #End Region #Region "Option statements" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Option Strict On </Code> Await TestAsync(code, changedCode, Add("Option Strict On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add2() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Explicit On Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add3() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Explicit On Option Infer On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add4() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On Option Explicit On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove1() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("Option Strict On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove2() As Task Dim code = <Code> Option Explicit On Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove3() As Task Dim code = <Code> Option Strict On Option Explicit On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove4() As Task Dim code = <Code> Option Strict On Option Infer On Option Explicit On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename1() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Strict Off </Code> Await TestAsync(code, changedCode, Rename("Option Strict Off")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename2() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Explicit On </Code> Await TestAsync(code, changedCode, Rename("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename3() As Task ' Note: This represents a change from the legacy VB code model where ' the following test would result in Remove event being fired for "Option Strict On" ' rather than a resolve. However, this should be more expected in the Roslyn code model ' because it doesn't fire on commit as it did in the legacy code model. Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Strict Goo </Code> Await TestAsync(code, changedCode, Rename("Option Strict Goo")) End Function #End Region #Region "File-level attributes" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> Imports System &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add2() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: AssemblyTitle("")&gt; &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add3() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; &lt;Assembly: AssemblyTitle("")&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add4() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: AssemblyTitle(""), Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add5() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True), Assembly: AssemblyTitle("")&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeSpecifier1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Module: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Unknown("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_AddArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("", "CLSCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_RemoveArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant&gt; </Code> Await TestAsync(code, changedCode, Remove("", "CLSCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_OmitArgument1() As Task Dim code = <Code> &lt;Goo("hello", Baz:=True)&gt; Class GooAttribute Inherits Attribute Sub New(Optional bar As String = Nothing) End Sub Public Property Baz As Boolean Get End Get Set(value As Boolean) End Set End Property End Class </Code> Dim changedCode = <Code> &lt;Goo(, Baz:=True)&gt; Class GooAttribute Inherits Attribute Sub New(Optional bar As String = Nothing) End Sub Public Property Baz As Boolean Get End Get Set(value As Boolean) End Set End Property End Class </Code> Await TestAsync(code, changedCode, Change(CodeModelEventType.Rename Or CodeModelEventType.Unknown, ""), ArgChange("Goo")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_RenameArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(IsCompliant:=True)&gt; </Code> Await TestAsync(code, changedCode, Rename("IsCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(False)&gt; </Code> Await TestAsync(code, changedCode, Unknown(""), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeArgument2() As Task Dim code = <Code> &lt;Assembly: Goo("")&gt; </Code> Dim changedCode = <Code> &lt;Assembly: Goo(0)&gt; </Code> Await TestAsync(code, changedCode, Unknown(""), ArgChange("Goo")) End Function #End Region #Region "Namespaces" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Namespace N </Code> Await TestAsync(code, changedCode, Add("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add2() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Namespace N End Namespace </Code> Await TestAsync(code, changedCode, Add("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add3() As Task Dim code = <Code> Namespace N1 End Namespace </Code> Dim changedCode = <Code> Namespace N1 Namespace N2 End Namespace </Code> Await TestAsync(code, changedCode, Add("N2", "N1")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove1() As Task Dim code = <Code> Namespace N </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("N", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove2() As Task Dim code = <Code> Namespace N End Namespace </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("N", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove3() As Task Dim code = <Code> Namespace N1 Namespace N2 End Namespace </Code> Dim changedCode = <Code> Namespace N1 End Namespace </Code> Await TestAsync(code, changedCode, Remove("N2", "N1")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Rename1() As Task Dim code = <Code> Namespace N1 End Namespace </Code> Dim changedCode = <Code> Namespace N2 End Namespace </Code> Await TestAsync(code, changedCode, Rename("N2")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Rename2() As Task Dim code = <Code> Namespace N1 Namespace N2 End Namespace End Namespace </Code> Dim changedCode = <Code> Namespace N1 Namespace N3 End Namespace End Namespace </Code> Await TestAsync(code, changedCode, Rename("N3")) End Function #End Region #Region "Classes" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Add("C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add2() As Task Dim code = <Code> Namespace N End Namespace </Code> Dim changedCode = <Code> Namespace N Class C End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("C", "N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add3() As Task Dim code = <Code> Namespace N Class B End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B Class C End Class End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("C", "B")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("C", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove2() As Task Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N End Namespace </Code> Await TestAsync(code, changedCode, Remove("C", "N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove3() As Task Dim code = <Code> Namespace N Class B Class C End Class End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class End Namespace </Code> Await TestAsync(code, changedCode, Remove("C", "B")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ReplaceWithTwoClasses1() As Task Dim code = <Code> Class D End Class </Code> Dim changedCode = <Code> Class B End Class Class C End Class </Code> Await TestAsync(code, changedCode, Unknown(Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ReplaceWithTwoClasses2() As Task Dim code = <Code> Namespace N Class D End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class Class C End Class End Namespace </Code> Await TestAsync(code, changedCode, Unknown("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ChangeBaseList() As Task Dim code = <Code> Namespace N Class B End Class Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class Class C Inherits B End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("Inherits", "C"), BaseChange("C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Rename1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class D End Class </Code> Await TestAsync(code, changedCode, Rename("D")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Rename2() As Task Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class D End Class End Namespace </Code> Await TestAsync(code, changedCode, Rename("D")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_AddBaseClass() As Task Dim code = <Code> Class attr End Class </Code> Dim changedCode = <Code> Class attr : Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("Inherits", "attr"), BaseChange("attr")) End Function #End Region #Region "Enums" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestEnum_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Enum Goo End Enum </Code> Await TestAsync(code, changedCode, Add("Goo")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestEnum_Rename1() As Task Dim code = <Code> Enum Goo End Enum </Code> Dim changedCode = <Code> Enum Bar End Enum </Code> Await TestAsync(code, changedCode, Rename("Bar")) End Function #End Region #Region "Fields" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Add("i", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add2() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer Dim j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add3() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add4() As Task Dim code = <Code> Class C Dim i, k As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, j, k As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add5() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Dim i, j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("i", "C"), Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove1() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("i", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove2() As Task Dim code = <Code> Class C Dim i As Integer Dim j As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove3() As Task Dim code = <Code> Class C Dim i, j As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove4() As Task Dim code = <Code> Class C Dim i, j, k As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, k As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove5() As Task Dim code = <Code> Class C Dim i, j As Integer End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("i", "C"), Remove("j", "C")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddAttributeToField() As Task Dim code = <Code> Class C Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.CLSCompliant", "goo")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddAttributeToTwoFields() As Task Dim code = <Code> Class C Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.CLSCompliant", "goo"), Add("System.CLSCompliant", "bar")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveAttributeFromField() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C Dim goo As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.CLSCompliant", "goo")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveAttributeFromTwoFields() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.CLSCompliant", "goo"), Remove("System.CLSCompliant", "bar")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_ChangeAttributeOnField() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo As Integer End Class </Code> ' Unknown event fires for attribute argument and attribute ArgChange event fires for each field Await TestAsync(code, changedCode, Unknown(""), ArgChange("System.CLSCompliant")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_ChangeAttributeOnTwoFields() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> ' Unknown event fires for attribute argument and attribute ArgChange event fires for each field Await TestAsync(code, changedCode, Unknown(""), ArgChange("System.CLSCompliant", "goo"), ArgChange("System.CLSCompliant", "bar")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddOneMoreAttribute() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False), System.NonSerialized()&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.NonSerialized", "goo"), Add("System.NonSerialized", "bar")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveOneAttribute() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False), System.NonSerialized()&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.NonSerialized", "goo"), Remove("System.NonSerialized", "bar")) End Function #End Region #Region "Methods" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_Add1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Sub M() End Sub End Class </Code> Await TestAsync(code, changedCode, Add("M", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_Remove1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("M", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_RemoveOperator1() As Task Dim code = <Code> Class C Shared Operator *(i As Integer, c As C) As C End Operator End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("*", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_ChangeType1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Function M() As Integer End Function End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_ChangeType2() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Function M() As Integer End Function End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("M")) End Function #End Region #Region "Parameters" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Add1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Add("i", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Add2() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(i As Integer, j As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Add("j", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Remove1() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M() End Sub End Class </Code> Await TestAsync(code, changedCode, Remove("i", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeModifier1() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(ByRef i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("i")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeModifier2() As Task Dim code = <Code> Class C Sub M(ByVal i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(ByRef i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("i")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeTypeToTypeCharacter() As Task Dim code = <Code> Class C Sub M(b As Boolean) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(b%) End Sub End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("b")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeTypeFromTypeCharacter() As Task Dim code = <Code> Class C Sub M(b%) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(b As Boolean) End Sub End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("b")) End Function #End Region #Region "Attribute Arguments" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestAttribute_AddArgument1() As Task Dim code = <Code> Imports System &lt;$$AttributeUsage()&gt; Class CAttribute Inherits Attribute End Class </Code> Dim changedCode = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All)&gt; Class CAttribute Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("", "AttributeUsage"), ArgChange("AttributeUsage")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestAttribute_AddArgument2() As Task Dim code = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All)&gt; Class CAttribute Inherits Attribute End Class </Code> Dim changedCode = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All, AllowMultiple:=False)&gt; Class CAttribute Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("AllowMultiple", "AttributeUsage"), ArgChange("AttributeUsage")) End Function #End Region #Region "Other" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestRenameInterfaceMethod() As Task Dim code = <Code> Interface IGoo Sub Goo() Function Bar() As Integer End Interface Class C Implements IGoo Public Sub Goo() Implements IGoo.Goo Throw New NotImplementedException() End Sub Public Function Bar() As Integer Implements IGoo.Bar Throw New NotImplementedException() End Function End Class </Code> Dim changedCode = <Code> Interface IGoo Sub Goo() Function Baz() As Integer End Interface Class C Implements IGoo Public Sub Goo() Implements IGoo.Goo Throw New NotImplementedException() End Sub Public Function Bar() As Integer Implements IGoo.Baz Throw New NotImplementedException() End Function End Class </Code> Await TestAsync(code, changedCode, Rename("Baz")) End Function <WorkItem(575666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575666")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestDontFireEventsForGarbage1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C AddHandler button1.Click, Async Sub(sender, e) textBox1.Clear() ' SumPageSizesAsync is a method that returns a Task. Await SumPageSizesAsync() textBox1.Text = vbCrLf &amp; "Control returned to button1_Click." End Sub End Class </Code> Await TestAsync(code, changedCode) End Function <WorkItem(578249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578249")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestDontFireEventsForGarbage2() As Task Dim code = <Code> Partial Class SomeClass Partial Private Sub Goo() End Sub Private Sub Goo() End Sub End Class </Code> Dim changedCode = <Code> Partial Class SomeClass Partial Private Sub Goo() End Sub Private Sub Goo() End Sub End Class Partial C </Code> Await TestAsync(code, changedCode) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestComparePropertyStatementBeforeMethodBase() As Task Dim code = <Code> Public MustInherit Class C1 Public Property PropertyA() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property Public Property PropertyB() As Integer Public MustOverride Property PropertyC() As Integer End Class </Code> Dim changedCode = <Code> Public MustInherit Class C1 Public MustOverride Property PropertyC() As Integer Public Property PropertyB() As Integer Public Property PropertyA() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property End Class </Code> Await TestAsync(code, changedCode, Unknown("C1")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler End Class </Code> Dim changedCode = <Code> Class Program Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_1() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Sub Met() End Sub Public Event cust As EventHandler End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met() End Sub Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_2() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler Public Sub Met() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Event cust As EventHandler Public Sub Met() End Sub Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_3() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler Public Sub Met() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met() End Sub Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareMethodsOnly() As Task Dim code = <Code> Class Program Public Sub Met() End Sub Public Sub Met1() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met1() End Sub Public Sub Met() End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function #End Region <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedMethodsInNamespace() As Task Dim code = <Code> Namespace N Sub M() End Sub End Namespace </Code> Dim changedCode = <Code> Namespace N Sub M() End Sub Sub M() End Sub End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedPropertiesInNamespace() As Task Dim code = <Code> Namespace N ReadOnly Property P As Integer = 42 End Namespace </Code> Dim changedCode = <Code> Namespace N ReadOnly Property P As Integer = 42 ReadOnly Property P As Integer = 42 End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedEventsInNamespace1() As Task Dim code = <Code> Namespace N Event E() End Namespace </Code> Dim changedCode = <Code> Namespace N Event E() Event E() End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedEventsInNamespace2() As Task Dim code = <Code> Namespace N Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Namespace </Code> Dim changedCode = <Code> Namespace N Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Namespace </Code> Await TestAsync(code, changedCode) 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.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class EventCollectorTests Inherits AbstractEventCollectorTests #Region "Imports statements" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Imports System </Code> Await TestAsync(code, changedCode, Add("System")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add2() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add3() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add4() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add5() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System.Linq, System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add6() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System, System.Linq Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Add7() As Task Dim code = <Code> Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System, S = System.Linq Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Add("System.Linq")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("System", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove2() As Task Dim code = <Code> Imports System.Linq Imports System Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove3() As Task Dim code = <Code> Imports System Imports System.Linq Imports System.Collections.Generic </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove4() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports System.Linq </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove5() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports System.Linq Class C End Class </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic End Class </Code> Await TestAsync(code, changedCode, Remove("System.Linq", Nothing), Remove("C", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Remove6() As Task Dim code = <Code> Imports System Imports System.Collections.Generic Imports &lt;xmlns:aw="http://www.adventure-works.com"&gt; Class C End Class </Code> Dim changedCode = <Code> Imports System Imports System.Collections.Generic Class C End Class </Code> ' Note: XML namespaces aren't supported by VB code model, so there should be no events when they're removed. Await TestAsync(code, changedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestImportsStatement_Rename1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> Imports System.Linq </Code> Await TestAsync(code, changedCode, Rename("System.Linq")) End Function #End Region #Region "Option statements" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Option Strict On </Code> Await TestAsync(code, changedCode, Add("Option Strict On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add2() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Explicit On Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add3() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Explicit On Option Infer On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Add4() As Task Dim code = <Code> Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On Option Explicit On </Code> Await TestAsync(code, changedCode, Add("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove1() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("Option Strict On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove2() As Task Dim code = <Code> Option Explicit On Option Strict On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove3() As Task Dim code = <Code> Option Strict On Option Explicit On Option Infer On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Remove4() As Task Dim code = <Code> Option Strict On Option Infer On Option Explicit On </Code> Dim changedCode = <Code> Option Strict On Option Infer On </Code> Await TestAsync(code, changedCode, Remove("Option Explicit On", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename1() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Strict Off </Code> Await TestAsync(code, changedCode, Rename("Option Strict Off")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename2() As Task Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Explicit On </Code> Await TestAsync(code, changedCode, Rename("Option Explicit On")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestOptionsStatement_Rename3() As Task ' Note: This represents a change from the legacy VB code model where ' the following test would result in Remove event being fired for "Option Strict On" ' rather than a resolve. However, this should be more expected in the Roslyn code model ' because it doesn't fire on commit as it did in the legacy code model. Dim code = <Code> Option Strict On </Code> Dim changedCode = <Code> Option Strict Goo </Code> Await TestAsync(code, changedCode, Rename("Option Strict Goo")) End Function #End Region #Region "File-level attributes" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add1() As Task Dim code = <Code> Imports System </Code> Dim changedCode = <Code> Imports System &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add2() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: AssemblyTitle("")&gt; &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add3() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; &lt;Assembly: AssemblyTitle("")&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add4() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: AssemblyTitle(""), Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_Add5() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True), Assembly: AssemblyTitle("")&gt; </Code> Await TestAsync(code, changedCode, Add("AssemblyTitle")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeSpecifier1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Module: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Unknown("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_AddArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAsync(code, changedCode, Add("", "CLSCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_RemoveArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant&gt; </Code> Await TestAsync(code, changedCode, Remove("", "CLSCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_OmitArgument1() As Task Dim code = <Code> &lt;Goo("hello", Baz:=True)&gt; Class GooAttribute Inherits Attribute Sub New(Optional bar As String = Nothing) End Sub Public Property Baz As Boolean Get End Get Set(value As Boolean) End Set End Property End Class </Code> Dim changedCode = <Code> &lt;Goo(, Baz:=True)&gt; Class GooAttribute Inherits Attribute Sub New(Optional bar As String = Nothing) End Sub Public Property Baz As Boolean Get End Get Set(value As Boolean) End Set End Property End Class </Code> Await TestAsync(code, changedCode, Change(CodeModelEventType.Rename Or CodeModelEventType.Unknown, ""), ArgChange("Goo")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_RenameArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(IsCompliant:=True)&gt; </Code> Await TestAsync(code, changedCode, Rename("IsCompliant"), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeArgument1() As Task Dim code = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(True)&gt; </Code> Dim changedCode = <Code> Imports System Imports System.Reflection &lt;Assembly: CLSCompliant(False)&gt; </Code> Await TestAsync(code, changedCode, Unknown(""), ArgChange("CLSCompliant")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestFileLevelAttribute_ChangeArgument2() As Task Dim code = <Code> &lt;Assembly: Goo("")&gt; </Code> Dim changedCode = <Code> &lt;Assembly: Goo(0)&gt; </Code> Await TestAsync(code, changedCode, Unknown(""), ArgChange("Goo")) End Function #End Region #Region "Namespaces" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Namespace N </Code> Await TestAsync(code, changedCode, Add("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add2() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Namespace N End Namespace </Code> Await TestAsync(code, changedCode, Add("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Add3() As Task Dim code = <Code> Namespace N1 End Namespace </Code> Dim changedCode = <Code> Namespace N1 Namespace N2 End Namespace </Code> Await TestAsync(code, changedCode, Add("N2", "N1")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove1() As Task Dim code = <Code> Namespace N </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("N", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove2() As Task Dim code = <Code> Namespace N End Namespace </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("N", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Remove3() As Task Dim code = <Code> Namespace N1 Namespace N2 End Namespace </Code> Dim changedCode = <Code> Namespace N1 End Namespace </Code> Await TestAsync(code, changedCode, Remove("N2", "N1")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Rename1() As Task Dim code = <Code> Namespace N1 End Namespace </Code> Dim changedCode = <Code> Namespace N2 End Namespace </Code> Await TestAsync(code, changedCode, Rename("N2")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestNamespace_Rename2() As Task Dim code = <Code> Namespace N1 Namespace N2 End Namespace End Namespace </Code> Dim changedCode = <Code> Namespace N1 Namespace N3 End Namespace End Namespace </Code> Await TestAsync(code, changedCode, Rename("N3")) End Function #End Region #Region "Classes" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Add("C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add2() As Task Dim code = <Code> Namespace N End Namespace </Code> Dim changedCode = <Code> Namespace N Class C End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("C", "N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Add3() As Task Dim code = <Code> Namespace N Class B End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B Class C End Class End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("C", "B")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> </Code> Await TestAsync(code, changedCode, Remove("C", Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove2() As Task Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N End Namespace </Code> Await TestAsync(code, changedCode, Remove("C", "N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Remove3() As Task Dim code = <Code> Namespace N Class B Class C End Class End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class End Namespace </Code> Await TestAsync(code, changedCode, Remove("C", "B")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ReplaceWithTwoClasses1() As Task Dim code = <Code> Class D End Class </Code> Dim changedCode = <Code> Class B End Class Class C End Class </Code> Await TestAsync(code, changedCode, Unknown(Nothing)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ReplaceWithTwoClasses2() As Task Dim code = <Code> Namespace N Class D End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class Class C End Class End Namespace </Code> Await TestAsync(code, changedCode, Unknown("N")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_ChangeBaseList() As Task Dim code = <Code> Namespace N Class B End Class Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class B End Class Class C Inherits B End Class End Namespace </Code> Await TestAsync(code, changedCode, Add("Inherits", "C"), BaseChange("C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Rename1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class D End Class </Code> Await TestAsync(code, changedCode, Rename("D")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_Rename2() As Task Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Dim changedCode = <Code> Namespace N Class D End Class End Namespace </Code> Await TestAsync(code, changedCode, Rename("D")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestClass_AddBaseClass() As Task Dim code = <Code> Class attr End Class </Code> Dim changedCode = <Code> Class attr : Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("Inherits", "attr"), BaseChange("attr")) End Function #End Region #Region "Enums" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestEnum_Add1() As Task Dim code = <Code> </Code> Dim changedCode = <Code> Enum Goo End Enum </Code> Await TestAsync(code, changedCode, Add("Goo")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestEnum_Rename1() As Task Dim code = <Code> Enum Goo End Enum </Code> Dim changedCode = <Code> Enum Bar End Enum </Code> Await TestAsync(code, changedCode, Rename("Bar")) End Function #End Region #Region "Fields" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Add("i", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add2() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer Dim j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add3() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add4() As Task Dim code = <Code> Class C Dim i, k As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, j, k As Integer End Class </Code> Await TestAsync(code, changedCode, Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Add5() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Dim i, j As Integer End Class </Code> Await TestAsync(code, changedCode, Add("i", "C"), Add("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove1() As Task Dim code = <Code> Class C Dim i As Integer End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("i", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove2() As Task Dim code = <Code> Class C Dim i As Integer Dim j As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove3() As Task Dim code = <Code> Class C Dim i, j As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove4() As Task Dim code = <Code> Class C Dim i, j, k As Integer End Class </Code> Dim changedCode = <Code> Class C Dim i, k As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("j", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_Remove5() As Task Dim code = <Code> Class C Dim i, j As Integer End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("i", "C"), Remove("j", "C")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddAttributeToField() As Task Dim code = <Code> Class C Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.CLSCompliant", "goo")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddAttributeToTwoFields() As Task Dim code = <Code> Class C Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.CLSCompliant", "goo"), Add("System.CLSCompliant", "bar")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveAttributeFromField() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C Dim goo As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.CLSCompliant", "goo")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveAttributeFromTwoFields() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.CLSCompliant", "goo"), Remove("System.CLSCompliant", "bar")) End Function <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_ChangeAttributeOnField() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo As Integer End Class </Code> ' Unknown event fires for attribute argument and attribute ArgChange event fires for each field Await TestAsync(code, changedCode, Unknown(""), ArgChange("System.CLSCompliant")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WorkItem(844611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844611")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_ChangeAttributeOnTwoFields() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim goo, bar As Integer End Class </Code> ' Unknown event fires for attribute argument and attribute ArgChange event fires for each field Await TestAsync(code, changedCode, Unknown(""), ArgChange("System.CLSCompliant", "goo"), ArgChange("System.CLSCompliant", "bar")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_AddOneMoreAttribute() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False), System.NonSerialized()&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Add("System.NonSerialized", "goo"), Add("System.NonSerialized", "bar")) End Function <WorkItem(1147865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147865")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestField_RemoveOneAttribute() As Task Dim code = <Code> Class C &lt;System.CLSCompliant(False), System.NonSerialized()&gt; Dim goo, bar As Integer End Class </Code> Dim changedCode = <Code> Class C &lt;System.CLSCompliant(False)&gt; Dim goo, bar As Integer End Class </Code> Await TestAsync(code, changedCode, Remove("System.NonSerialized", "goo"), Remove("System.NonSerialized", "bar")) End Function #End Region #Region "Methods" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_Add1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C Sub M() End Sub End Class </Code> Await TestAsync(code, changedCode, Add("M", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_Remove1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("M", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_RemoveOperator1() As Task Dim code = <Code> Class C Shared Operator *(i As Integer, c As C) As C End Operator End Class </Code> Dim changedCode = <Code> Class C End Class </Code> Await TestAsync(code, changedCode, Remove("*", "C")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_ChangeType1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Function M() As Integer End Function End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestMethod_ChangeType2() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Function M() As Integer End Function End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("M")) End Function #End Region #Region "Parameters" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Add1() As Task Dim code = <Code> Class C Sub M() End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Add("i", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Add2() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(i As Integer, j As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Add("j", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_Remove1() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M() End Sub End Class </Code> Await TestAsync(code, changedCode, Remove("i", "M")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeModifier1() As Task Dim code = <Code> Class C Sub M(i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(ByRef i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("i")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeModifier2() As Task Dim code = <Code> Class C Sub M(ByVal i As Integer) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(ByRef i As Integer) End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("i")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeTypeToTypeCharacter() As Task Dim code = <Code> Class C Sub M(b As Boolean) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(b%) End Sub End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("b")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestParameter_ChangeTypeFromTypeCharacter() As Task Dim code = <Code> Class C Sub M(b%) End Sub End Class </Code> Dim changedCode = <Code> Class C Sub M(b As Boolean) End Sub End Class </Code> Await TestAsync(code, changedCode, TypeRefChange("b")) End Function #End Region #Region "Attribute Arguments" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestAttribute_AddArgument1() As Task Dim code = <Code> Imports System &lt;$$AttributeUsage()&gt; Class CAttribute Inherits Attribute End Class </Code> Dim changedCode = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All)&gt; Class CAttribute Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("", "AttributeUsage"), ArgChange("AttributeUsage")) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestAttribute_AddArgument2() As Task Dim code = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All)&gt; Class CAttribute Inherits Attribute End Class </Code> Dim changedCode = <Code> Imports System &lt;$$AttributeUsage(AttributeTargets.All, AllowMultiple:=False)&gt; Class CAttribute Inherits Attribute End Class </Code> Await TestAsync(code, changedCode, Add("AllowMultiple", "AttributeUsage"), ArgChange("AttributeUsage")) End Function #End Region #Region "Other" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestRenameInterfaceMethod() As Task Dim code = <Code> Interface IGoo Sub Goo() Function Bar() As Integer End Interface Class C Implements IGoo Public Sub Goo() Implements IGoo.Goo Throw New NotImplementedException() End Sub Public Function Bar() As Integer Implements IGoo.Bar Throw New NotImplementedException() End Function End Class </Code> Dim changedCode = <Code> Interface IGoo Sub Goo() Function Baz() As Integer End Interface Class C Implements IGoo Public Sub Goo() Implements IGoo.Goo Throw New NotImplementedException() End Sub Public Function Bar() As Integer Implements IGoo.Baz Throw New NotImplementedException() End Function End Class </Code> Await TestAsync(code, changedCode, Rename("Baz")) End Function <WorkItem(575666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575666")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestDontFireEventsForGarbage1() As Task Dim code = <Code> Class C End Class </Code> Dim changedCode = <Code> Class C AddHandler button1.Click, Async Sub(sender, e) textBox1.Clear() ' SumPageSizesAsync is a method that returns a Task. Await SumPageSizesAsync() textBox1.Text = vbCrLf &amp; "Control returned to button1_Click." End Sub End Class </Code> Await TestAsync(code, changedCode) End Function <WorkItem(578249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578249")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestDontFireEventsForGarbage2() As Task Dim code = <Code> Partial Class SomeClass Partial Private Sub Goo() End Sub Private Sub Goo() End Sub End Class </Code> Dim changedCode = <Code> Partial Class SomeClass Partial Private Sub Goo() End Sub Private Sub Goo() End Sub End Class Partial C </Code> Await TestAsync(code, changedCode) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestComparePropertyStatementBeforeMethodBase() As Task Dim code = <Code> Public MustInherit Class C1 Public Property PropertyA() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property Public Property PropertyB() As Integer Public MustOverride Property PropertyC() As Integer End Class </Code> Dim changedCode = <Code> Public MustInherit Class C1 Public MustOverride Property PropertyC() As Integer Public Property PropertyB() As Integer Public Property PropertyA() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property End Class </Code> Await TestAsync(code, changedCode, Unknown("C1")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler End Class </Code> Dim changedCode = <Code> Class Program Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_1() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Sub Met() End Sub Public Event cust As EventHandler End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met() End Sub Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_2() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler Public Sub Met() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Event cust As EventHandler Public Sub Met() End Sub Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareEventStatementBeforeMethodBase_WithMethods_3() As Task Dim code = <Code> Class Program Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event Public Event cust As EventHandler Public Sub Met() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met() End Sub Public Event cust As EventHandler Public Custom Event ServerChange As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function <WorkItem(1101185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101185")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function TestCompareMethodsOnly() As Task Dim code = <Code> Class Program Public Sub Met() End Sub Public Sub Met1() End Sub End Class </Code> Dim changedCode = <Code> Class Program Public Sub Met1() End Sub Public Sub Met() End Sub End Class </Code> Await TestAsync(code, changedCode, Unknown("Program")) End Function #End Region <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedMethodsInNamespace() As Task Dim code = <Code> Namespace N Sub M() End Sub End Namespace </Code> Dim changedCode = <Code> Namespace N Sub M() End Sub Sub M() End Sub End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedPropertiesInNamespace() As Task Dim code = <Code> Namespace N ReadOnly Property P As Integer = 42 End Namespace </Code> Dim changedCode = <Code> Namespace N ReadOnly Property P As Integer = 42 ReadOnly Property P As Integer = 42 End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedEventsInNamespace1() As Task Dim code = <Code> Namespace N Event E() End Namespace </Code> Dim changedCode = <Code> Namespace N Event E() Event E() End Namespace </Code> Await TestAsync(code, changedCode) End Function <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelEvents)> Public Async Function DontCrashOnDuplicatedEventsInNamespace2() As Task Dim code = <Code> Namespace N Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Namespace </Code> Dim changedCode = <Code> Namespace N Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Namespace </Code> Await TestAsync(code, changedCode) 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,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Text/xlf/TextEditorResources.de.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="de" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">Die Momentaufnahme weist nicht die angegebene Position auf.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">Die Momentaufnahme weist nicht die angegebene Spanne auf.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer ist kein SourceTextContainer, der aus einem ITextBuffer erstellt wurde.</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="de" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">Die Momentaufnahme weist nicht die angegebene Position auf.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">Die Momentaufnahme weist nicht die angegebene Spanne auf.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer ist kein SourceTextContainer, der aus einem ITextBuffer erstellt wurde.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Implementation/AutomaticCompletion/IBraceCompletionServiceFactory.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal interface IBraceCompletionServiceFactory : ILanguageService { Task<IBraceCompletionService?> TryGetServiceAsync(Document document, int openingPosition, char openingBrace, 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. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion { internal interface IBraceCompletionServiceFactory : ILanguageService { Task<IBraceCompletionService?> TryGetServiceAsync(Document document, int openingPosition, char openingBrace, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Emit/GenericNamespaceTypeInstanceReference.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 Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a generic type instantiation that is not nested. ''' e.g. MyNamespace.A{int} ''' </summary> Friend NotInheritable Class GenericNamespaceTypeInstanceReference Inherits GenericTypeInstanceReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Microsoft.Cci.IGenericTypeInstanceReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Microsoft.Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Microsoft.Cci.INestedTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Microsoft.Cci.ISpecializedNestedTypeReference Get Return Nothing 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 Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a reference to a generic type instantiation that is not nested. ''' e.g. MyNamespace.A{int} ''' </summary> Friend NotInheritable Class GenericNamespaceTypeInstanceReference Inherits GenericTypeInstanceReference Public Sub New(underlyingNamedType As NamedTypeSymbol) MyBase.New(underlyingNamedType) End Sub Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Microsoft.Cci.IGenericTypeInstanceReference Get Return Me End Get End Property Public Overrides ReadOnly Property AsNamespaceTypeReference As Microsoft.Cci.INamespaceTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsNestedTypeReference As Microsoft.Cci.INestedTypeReference Get Return Nothing End Get End Property Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Microsoft.Cci.ISpecializedNestedTypeReference Get Return Nothing End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used for interiors of documentation comment ''' </summary> Friend MustInherit Class DocumentationCommentBinder Inherits Binder Protected Sub New(containingBinder As Binder, commentedSymbol As Symbol) MyBase.New(containingBinder) CheckBinderSymbolRelationship(containingBinder, commentedSymbol) Me.CommentedSymbol = commentedSymbol End Sub ''' <summary> ''' Assuming there is one, the containing member of the binder is the commented symbol if and only if ''' the commented symbol is a non-delegate named type. (Otherwise, it is the containing type or namespace of the commented symbol.) ''' </summary> ''' <remarks> ''' Delegates don't have user-defined members, so it makes more sense to treat ''' them like methods. ''' </remarks> <Conditional("DEBUG")> Private Shared Sub CheckBinderSymbolRelationship(containingBinder As Binder, commentedSymbol As Symbol) If commentedSymbol Is Nothing Then Return End If Dim commentedNamedType = TryCast(commentedSymbol, NamedTypeSymbol) Dim binderContainingMember As Symbol = containingBinder.ContainingMember If commentedNamedType IsNot Nothing AndAlso commentedNamedType.TypeKind <> TypeKind.Delegate Then Debug.Assert(binderContainingMember = commentedSymbol) ElseIf commentedSymbol.ContainingType IsNot Nothing Then Debug.Assert(TypeSymbol.Equals(DirectCast(binderContainingMember, TypeSymbol), commentedSymbol.ContainingType, TypeCompareKind.ConsiderEverything)) Else ' It's not worth writing a complicated check that handles merged namespaces. Debug.Assert(binderContainingMember <> commentedSymbol) Debug.Assert(binderContainingMember.Kind = SymbolKind.Namespace) End If End Sub Friend Enum BinderType None Cref NameInTypeParamRef NameInTypeParam NameInParamOrParamRef End Enum Public Shared Function IsIntrinsicTypeForDocumentationComment(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.ShortKeyword, SyntaxKind.UShortKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.LongKeyword, SyntaxKind.ULongKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.SingleKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.SByteKeyword, SyntaxKind.ByteKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.CharKeyword, SyntaxKind.DateKeyword, SyntaxKind.StringKeyword Return True Case Else Return False End Select End Function Friend Shared Function GetBinderTypeForNameAttribute(node As BaseXmlAttributeSyntax) As DocumentationCommentBinder.BinderType Return GetBinderTypeForNameAttribute(GetParentXmlElementName(node)) End Function Friend Shared Function GetBinderTypeForNameAttribute(parentNodeName As String) As DocumentationCommentBinder.BinderType If parentNodeName IsNot Nothing Then If DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterElementName, True) OrElse DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterReferenceElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInParamOrParamRef ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInTypeParam ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterReferenceElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInTypeParamRef End If End If Return DocumentationCommentBinder.BinderType.None End Function Friend Shared Function GetParentXmlElementName(attr As BaseXmlAttributeSyntax) As String Dim parent As VisualBasicSyntaxNode = attr.Parent If parent Is Nothing Then Return Nothing End If Select Case parent.Kind Case SyntaxKind.XmlEmptyElement Dim element = DirectCast(parent, XmlEmptyElementSyntax) If element.Name.Kind <> SyntaxKind.XmlName Then Return Nothing End If Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText Case SyntaxKind.XmlElementStartTag Dim element = DirectCast(parent, XmlElementStartTagSyntax) If element.Name.Kind <> SyntaxKind.XmlName Then Return Nothing End If Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText End Select Return Nothing End Function ''' <summary> ''' Symbol commented with the documentation comment handled by this binder. In general, ''' all name lookup is being performed in context of this symbol's containing symbol. ''' We still need this symbol, though, to be able to find type parameters or parameters ''' referenced from 'param', 'paramref', 'typeparam' and 'typeparamref' tags. ''' </summary> Protected ReadOnly CommentedSymbol As Symbol Friend Overrides Function BindXmlNameAttributeValue(identifier As IdentifierNameSyntax, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Protected Shared Function FindSymbolInSymbolArray(Of TSymbol As Symbol)( name As String, symbols As ImmutableArray(Of TSymbol)) As ImmutableArray(Of Symbol) If Not symbols.IsEmpty Then For Each p In symbols If IdentifierComparison.Equals(name, p.Name) Then Return ImmutableArray.Create(Of Symbol)(p) End If Next End If Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.UseBaseReferenceAccessibility End Function ''' <summary> ''' Removes from symbol collection overridden methods or properties ''' </summary> Protected Shared Sub RemoveOverriddenMethodsAndProperties(symbols As ArrayBuilder(Of Symbol)) If symbols Is Nothing OrElse symbols.Count < 2 Then Return End If ' Do we have any method or property? Dim originalDef2Symbol As Dictionary(Of Symbol, Integer) = Nothing For i = 0 To symbols.Count - 1 Dim sym As Symbol = symbols(i) Select Case sym.Kind Case SymbolKind.Method, SymbolKind.Property If originalDef2Symbol Is Nothing Then originalDef2Symbol = New Dictionary(Of Symbol, Integer)() End If originalDef2Symbol.Add(sym.OriginalDefinition, i) End Select Next If originalDef2Symbol Is Nothing Then Return End If ' Do we need to remove any? Dim indices2remove As ArrayBuilder(Of Integer) = Nothing For i = 0 To symbols.Count - 1 Dim index As Integer = -1 Dim sym As Symbol = symbols(i) Select Case sym.Kind Case SymbolKind.Method ' Remove overridden methods Dim method = DirectCast(sym.OriginalDefinition, MethodSymbol) While True method = method.OverriddenMethod If method Is Nothing Then Exit While End If If originalDef2Symbol.TryGetValue(method, index) Then If indices2remove Is Nothing Then indices2remove = ArrayBuilder(Of Integer).GetInstance End If indices2remove.Add(index) End If End While Case SymbolKind.Property ' Remove overridden properties Dim prop = DirectCast(sym.OriginalDefinition, PropertySymbol) While True prop = prop.OverriddenProperty If prop Is Nothing Then Exit While End If If originalDef2Symbol.TryGetValue(prop, index) Then If indices2remove Is Nothing Then indices2remove = ArrayBuilder(Of Integer).GetInstance End If indices2remove.Add(index) End If End While End Select Next If indices2remove Is Nothing Then Return End If ' remove elements by indices from 'indices2remove' For i = 0 To indices2remove.Count - 1 symbols(indices2remove(i)) = Nothing Next Dim target As Integer = 0 For source = 0 To symbols.Count - 1 Dim sym As Symbol = symbols(source) If sym IsNot Nothing Then symbols(target) = sym target += 1 End If Next symbols.Clip(target) indices2remove.Free() 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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used for interiors of documentation comment ''' </summary> Friend MustInherit Class DocumentationCommentBinder Inherits Binder Protected Sub New(containingBinder As Binder, commentedSymbol As Symbol) MyBase.New(containingBinder) CheckBinderSymbolRelationship(containingBinder, commentedSymbol) Me.CommentedSymbol = commentedSymbol End Sub ''' <summary> ''' Assuming there is one, the containing member of the binder is the commented symbol if and only if ''' the commented symbol is a non-delegate named type. (Otherwise, it is the containing type or namespace of the commented symbol.) ''' </summary> ''' <remarks> ''' Delegates don't have user-defined members, so it makes more sense to treat ''' them like methods. ''' </remarks> <Conditional("DEBUG")> Private Shared Sub CheckBinderSymbolRelationship(containingBinder As Binder, commentedSymbol As Symbol) If commentedSymbol Is Nothing Then Return End If Dim commentedNamedType = TryCast(commentedSymbol, NamedTypeSymbol) Dim binderContainingMember As Symbol = containingBinder.ContainingMember If commentedNamedType IsNot Nothing AndAlso commentedNamedType.TypeKind <> TypeKind.Delegate Then Debug.Assert(binderContainingMember = commentedSymbol) ElseIf commentedSymbol.ContainingType IsNot Nothing Then Debug.Assert(TypeSymbol.Equals(DirectCast(binderContainingMember, TypeSymbol), commentedSymbol.ContainingType, TypeCompareKind.ConsiderEverything)) Else ' It's not worth writing a complicated check that handles merged namespaces. Debug.Assert(binderContainingMember <> commentedSymbol) Debug.Assert(binderContainingMember.Kind = SymbolKind.Namespace) End If End Sub Friend Enum BinderType None Cref NameInTypeParamRef NameInTypeParam NameInParamOrParamRef End Enum Public Shared Function IsIntrinsicTypeForDocumentationComment(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.ShortKeyword, SyntaxKind.UShortKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.LongKeyword, SyntaxKind.ULongKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.SingleKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.SByteKeyword, SyntaxKind.ByteKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.CharKeyword, SyntaxKind.DateKeyword, SyntaxKind.StringKeyword Return True Case Else Return False End Select End Function Friend Shared Function GetBinderTypeForNameAttribute(node As BaseXmlAttributeSyntax) As DocumentationCommentBinder.BinderType Return GetBinderTypeForNameAttribute(GetParentXmlElementName(node)) End Function Friend Shared Function GetBinderTypeForNameAttribute(parentNodeName As String) As DocumentationCommentBinder.BinderType If parentNodeName IsNot Nothing Then If DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterElementName, True) OrElse DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.ParameterReferenceElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInParamOrParamRef ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInTypeParam ElseIf DocumentationCommentXmlNames.ElementEquals(parentNodeName, DocumentationCommentXmlNames.TypeParameterReferenceElementName, True) Then Return DocumentationCommentBinder.BinderType.NameInTypeParamRef End If End If Return DocumentationCommentBinder.BinderType.None End Function Friend Shared Function GetParentXmlElementName(attr As BaseXmlAttributeSyntax) As String Dim parent As VisualBasicSyntaxNode = attr.Parent If parent Is Nothing Then Return Nothing End If Select Case parent.Kind Case SyntaxKind.XmlEmptyElement Dim element = DirectCast(parent, XmlEmptyElementSyntax) If element.Name.Kind <> SyntaxKind.XmlName Then Return Nothing End If Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText Case SyntaxKind.XmlElementStartTag Dim element = DirectCast(parent, XmlElementStartTagSyntax) If element.Name.Kind <> SyntaxKind.XmlName Then Return Nothing End If Return DirectCast(element.Name, XmlNameSyntax).LocalName.ValueText End Select Return Nothing End Function ''' <summary> ''' Symbol commented with the documentation comment handled by this binder. In general, ''' all name lookup is being performed in context of this symbol's containing symbol. ''' We still need this symbol, though, to be able to find type parameters or parameters ''' referenced from 'param', 'paramref', 'typeparam' and 'typeparamref' tags. ''' </summary> Protected ReadOnly CommentedSymbol As Symbol Friend Overrides Function BindXmlNameAttributeValue(identifier As IdentifierNameSyntax, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As BindingDiagnosticBag, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) Throw ExceptionUtilities.Unreachable End Function Protected Shared Function FindSymbolInSymbolArray(Of TSymbol As Symbol)( name As String, symbols As ImmutableArray(Of TSymbol)) As ImmutableArray(Of Symbol) If Not symbols.IsEmpty Then For Each p In symbols If IdentifierComparison.Equals(name, p.Name) Then Return ImmutableArray.Create(Of Symbol)(p) End If Next End If Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.UseBaseReferenceAccessibility End Function ''' <summary> ''' Removes from symbol collection overridden methods or properties ''' </summary> Protected Shared Sub RemoveOverriddenMethodsAndProperties(symbols As ArrayBuilder(Of Symbol)) If symbols Is Nothing OrElse symbols.Count < 2 Then Return End If ' Do we have any method or property? Dim originalDef2Symbol As Dictionary(Of Symbol, Integer) = Nothing For i = 0 To symbols.Count - 1 Dim sym As Symbol = symbols(i) Select Case sym.Kind Case SymbolKind.Method, SymbolKind.Property If originalDef2Symbol Is Nothing Then originalDef2Symbol = New Dictionary(Of Symbol, Integer)() End If originalDef2Symbol.Add(sym.OriginalDefinition, i) End Select Next If originalDef2Symbol Is Nothing Then Return End If ' Do we need to remove any? Dim indices2remove As ArrayBuilder(Of Integer) = Nothing For i = 0 To symbols.Count - 1 Dim index As Integer = -1 Dim sym As Symbol = symbols(i) Select Case sym.Kind Case SymbolKind.Method ' Remove overridden methods Dim method = DirectCast(sym.OriginalDefinition, MethodSymbol) While True method = method.OverriddenMethod If method Is Nothing Then Exit While End If If originalDef2Symbol.TryGetValue(method, index) Then If indices2remove Is Nothing Then indices2remove = ArrayBuilder(Of Integer).GetInstance End If indices2remove.Add(index) End If End While Case SymbolKind.Property ' Remove overridden properties Dim prop = DirectCast(sym.OriginalDefinition, PropertySymbol) While True prop = prop.OverriddenProperty If prop Is Nothing Then Exit While End If If originalDef2Symbol.TryGetValue(prop, index) Then If indices2remove Is Nothing Then indices2remove = ArrayBuilder(Of Integer).GetInstance End If indices2remove.Add(index) End If End While End Select Next If indices2remove Is Nothing Then Return End If ' remove elements by indices from 'indices2remove' For i = 0 To indices2remove.Count - 1 symbols(indices2remove(i)) = Nothing Next Dim target As Integer = 0 For source = 0 To symbols.Count - 1 Dim sym As Symbol = symbols(source) If sym IsNot Nothing Then symbols(target) = sym target += 1 End If Next symbols.Clip(target) indices2remove.Free() End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.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.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ConstructorSymbolReferenceFinder : AbstractReferenceFinder<IMethodSymbol> { public static readonly ConstructorSymbolReferenceFinder Instance = new(); private ConstructorSymbolReferenceFinder() { } protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => true, MethodKind.StaticConstructor => true, _ => false, }; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var typeName = symbol.ContainingType.Name; var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, typeName).ConfigureAwait(false); var documentsWithType = await FindDocumentsAsync(project, documents, symbol.ContainingType.SpecialType.ToPredefinedType(), cancellationToken).ConfigureAwait(false); var documentsWithAttribute = TryGetNameWithoutAttributeSuffix(typeName, project.LanguageServices.GetRequiredService<ISyntaxFactsService>(), out var simpleName) ? await FindDocumentsAsync(project, documents, cancellationToken, simpleName).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithImplicitObjectCreations = symbol.MethodKind == MethodKind.Constructor ? await FindDocumentsWithImplicitObjectCreationExpressionAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithType, documentsWithImplicitObjectCreations, documentsWithAttribute, documentsWithGlobalAttributes); } private static bool IsPotentialReference( PredefinedType predefinedType, ISyntaxFactsService syntaxFacts, SyntaxToken token) { return syntaxFacts.TryGetPredefinedType(token, out var actualType) && predefinedType == actualType; } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol methodSymbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindAllReferencesInDocumentAsync(methodSymbol, document, semanticModel, cancellationToken); } internal async ValueTask<ImmutableArray<FinderLocation>> FindAllReferencesInDocumentAsync( IMethodSymbol methodSymbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var findParentNode = GetNamedTypeOrConstructorFindParentNodeFunction(document, methodSymbol); var normalReferences = await FindReferencesInDocumentWorkerAsync(methodSymbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var nonAliasTypeReferences = await NamedTypeSymbolReferenceFinder.FindNonAliasReferencesAsync(methodSymbol.ContainingType, document, semanticModel, cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync( nonAliasTypeReferences, methodSymbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, methodSymbol, cancellationToken).ConfigureAwait(false); return normalReferences.Concat(aliasReferences, suppressionReferences); } private async Task<ImmutableArray<FinderLocation>> FindReferencesInDocumentWorkerAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, Func<SyntaxToken, SyntaxNode>? findParentNode, CancellationToken cancellationToken) { var ordinaryRefs = await FindOrdinaryReferencesAsync(symbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var attributeRefs = await FindAttributeReferencesAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var predefinedTypeRefs = await FindPredefinedTypeReferencesAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var implicitObjectCreationMatches = await FindReferencesInImplicitObjectCreationExpressionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); return ordinaryRefs.Concat(attributeRefs, predefinedTypeRefs, implicitObjectCreationMatches); } private static ValueTask<ImmutableArray<FinderLocation>> FindOrdinaryReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, Func<SyntaxToken, SyntaxNode>? findParentNode, CancellationToken cancellationToken) { var name = symbol.ContainingType.Name; return FindReferencesInDocumentUsingIdentifierAsync( symbol, name, document, semanticModel, findParentNode, cancellationToken); } private static ValueTask<ImmutableArray<FinderLocation>> FindPredefinedTypeReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var predefinedType = symbol.ContainingType.SpecialType.ToPredefinedType(); if (predefinedType == PredefinedType.None) { return new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty); } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return FindReferencesInDocumentAsync(symbol, document, semanticModel, t => IsPotentialReference(predefinedType, syntaxFacts, t), cancellationToken); } private static ValueTask<ImmutableArray<FinderLocation>> FindAttributeReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return TryGetNameWithoutAttributeSuffix(symbol.ContainingType.Name, syntaxFacts, out var simpleName) ? FindReferencesInDocumentUsingIdentifierAsync(symbol, simpleName, document, semanticModel, cancellationToken) : new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty); } private Task<ImmutableArray<FinderLocation>> FindReferencesInImplicitObjectCreationExpressionAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { // Only check `new (...)` calls that supply enough arguments to match all the required parameters for the constructor. var minimumArgumentCount = symbol.Parameters.Count(p => !p.IsOptional && !p.IsParams); var maximumArgumentCount = symbol.Parameters.Length > 0 && symbol.Parameters.Last().IsParams ? int.MaxValue : symbol.Parameters.Length; var exactArgumentCount = symbol.Parameters.Any(p => p.IsOptional || p.IsParams) ? -1 : symbol.Parameters.Length; return FindReferencesInDocumentAsync(document, IsRelevantDocument, CollectMatchingReferences, cancellationToken); static bool IsRelevantDocument(SyntaxTreeIndex syntaxTreeInfo) => syntaxTreeInfo.ContainsImplicitObjectCreation; void CollectMatchingReferences( SyntaxNode node, ISyntaxFactsService syntaxFacts, ISemanticFactsService semanticFacts, ArrayBuilder<FinderLocation> locations) { if (!syntaxFacts.IsImplicitObjectCreationExpression(node)) return; // if there are too few or too many arguments, then don't bother checking. var actualArgumentCount = syntaxFacts.GetArgumentsOfObjectCreationExpression(node).Count; if (actualArgumentCount < minimumArgumentCount || actualArgumentCount > maximumArgumentCount) return; // if we need an exact count then make sure that the count we have fits the count we need. if (exactArgumentCount != -1 && exactArgumentCount != actualArgumentCount) return; var constructor = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol; if (Matches(constructor, symbol)) { var location = node.GetFirstToken().GetLocation(); var symbolUsageInfo = GetSymbolUsageInfo(node, semanticModel, syntaxFacts, semanticFacts, cancellationToken); locations.Add(new FinderLocation(node, new ReferenceLocation( document, alias: null, location, isImplicit: true, symbolUsageInfo, GetAdditionalFindUsagesProperties(node, semanticModel, syntaxFacts), CandidateReason.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. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ConstructorSymbolReferenceFinder : AbstractReferenceFinder<IMethodSymbol> { public static readonly ConstructorSymbolReferenceFinder Instance = new(); private ConstructorSymbolReferenceFinder() { } protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => true, MethodKind.StaticConstructor => true, _ => false, }; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var typeName = symbol.ContainingType.Name; var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, typeName).ConfigureAwait(false); var documentsWithType = await FindDocumentsAsync(project, documents, symbol.ContainingType.SpecialType.ToPredefinedType(), cancellationToken).ConfigureAwait(false); var documentsWithAttribute = TryGetNameWithoutAttributeSuffix(typeName, project.LanguageServices.GetRequiredService<ISyntaxFactsService>(), out var simpleName) ? await FindDocumentsAsync(project, documents, cancellationToken, simpleName).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithImplicitObjectCreations = symbol.MethodKind == MethodKind.Constructor ? await FindDocumentsWithImplicitObjectCreationExpressionAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithType, documentsWithImplicitObjectCreations, documentsWithAttribute, documentsWithGlobalAttributes); } private static bool IsPotentialReference( PredefinedType predefinedType, ISyntaxFactsService syntaxFacts, SyntaxToken token) { return syntaxFacts.TryGetPredefinedType(token, out var actualType) && predefinedType == actualType; } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol methodSymbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindAllReferencesInDocumentAsync(methodSymbol, document, semanticModel, cancellationToken); } internal async ValueTask<ImmutableArray<FinderLocation>> FindAllReferencesInDocumentAsync( IMethodSymbol methodSymbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var findParentNode = GetNamedTypeOrConstructorFindParentNodeFunction(document, methodSymbol); var normalReferences = await FindReferencesInDocumentWorkerAsync(methodSymbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var nonAliasTypeReferences = await NamedTypeSymbolReferenceFinder.FindNonAliasReferencesAsync(methodSymbol.ContainingType, document, semanticModel, cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync( nonAliasTypeReferences, methodSymbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, methodSymbol, cancellationToken).ConfigureAwait(false); return normalReferences.Concat(aliasReferences, suppressionReferences); } private async Task<ImmutableArray<FinderLocation>> FindReferencesInDocumentWorkerAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, Func<SyntaxToken, SyntaxNode>? findParentNode, CancellationToken cancellationToken) { var ordinaryRefs = await FindOrdinaryReferencesAsync(symbol, document, semanticModel, findParentNode, cancellationToken).ConfigureAwait(false); var attributeRefs = await FindAttributeReferencesAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var predefinedTypeRefs = await FindPredefinedTypeReferencesAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var implicitObjectCreationMatches = await FindReferencesInImplicitObjectCreationExpressionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); return ordinaryRefs.Concat(attributeRefs, predefinedTypeRefs, implicitObjectCreationMatches); } private static ValueTask<ImmutableArray<FinderLocation>> FindOrdinaryReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, Func<SyntaxToken, SyntaxNode>? findParentNode, CancellationToken cancellationToken) { var name = symbol.ContainingType.Name; return FindReferencesInDocumentUsingIdentifierAsync( symbol, name, document, semanticModel, findParentNode, cancellationToken); } private static ValueTask<ImmutableArray<FinderLocation>> FindPredefinedTypeReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var predefinedType = symbol.ContainingType.SpecialType.ToPredefinedType(); if (predefinedType == PredefinedType.None) { return new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty); } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return FindReferencesInDocumentAsync(symbol, document, semanticModel, t => IsPotentialReference(predefinedType, syntaxFacts, t), cancellationToken); } private static ValueTask<ImmutableArray<FinderLocation>> FindAttributeReferencesAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return TryGetNameWithoutAttributeSuffix(symbol.ContainingType.Name, syntaxFacts, out var simpleName) ? FindReferencesInDocumentUsingIdentifierAsync(symbol, simpleName, document, semanticModel, cancellationToken) : new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty); } private Task<ImmutableArray<FinderLocation>> FindReferencesInImplicitObjectCreationExpressionAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { // Only check `new (...)` calls that supply enough arguments to match all the required parameters for the constructor. var minimumArgumentCount = symbol.Parameters.Count(p => !p.IsOptional && !p.IsParams); var maximumArgumentCount = symbol.Parameters.Length > 0 && symbol.Parameters.Last().IsParams ? int.MaxValue : symbol.Parameters.Length; var exactArgumentCount = symbol.Parameters.Any(p => p.IsOptional || p.IsParams) ? -1 : symbol.Parameters.Length; return FindReferencesInDocumentAsync(document, IsRelevantDocument, CollectMatchingReferences, cancellationToken); static bool IsRelevantDocument(SyntaxTreeIndex syntaxTreeInfo) => syntaxTreeInfo.ContainsImplicitObjectCreation; void CollectMatchingReferences( SyntaxNode node, ISyntaxFactsService syntaxFacts, ISemanticFactsService semanticFacts, ArrayBuilder<FinderLocation> locations) { if (!syntaxFacts.IsImplicitObjectCreationExpression(node)) return; // if there are too few or too many arguments, then don't bother checking. var actualArgumentCount = syntaxFacts.GetArgumentsOfObjectCreationExpression(node).Count; if (actualArgumentCount < minimumArgumentCount || actualArgumentCount > maximumArgumentCount) return; // if we need an exact count then make sure that the count we have fits the count we need. if (exactArgumentCount != -1 && exactArgumentCount != actualArgumentCount) return; var constructor = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol; if (Matches(constructor, symbol)) { var location = node.GetFirstToken().GetLocation(); var symbolUsageInfo = GetSymbolUsageInfo(node, semanticModel, syntaxFacts, semanticFacts, cancellationToken); locations.Add(new FinderLocation(node, new ReferenceLocation( document, alias: null, location, isImplicit: true, symbolUsageInfo, GetAdditionalFindUsagesProperties(node, semanticModel, syntaxFacts), CandidateReason.None))); } } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/VisualBasicTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.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.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class ObjectCreationExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(ObjectCreationExpressionSignatureHelpProvider) End Function #Region "Regular tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickString() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:="Hello"$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickInteger() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:=1$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParametersMethodXmlComments() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo. See <see cref="System.Object"/> ''' </summary> Sub New() End Sub Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", "Summary for Goo. See Object", Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlCommentsOn1() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b</param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param a", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(545931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545931")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUnsupportedParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new String($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char())", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(c As Char, count As Integer)", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char(), startIndex As Integer, length As Integer)", currentParameterIndex:=0)) ' All the unsafe pointer overloads should be missing in VB Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlComentsOn2() As Task Dim markup = <a><![CDATA[ Imports System Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b. See <see cref="System.IAsyncResult"/></param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param b. See IAsyncResult", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParen() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParameters() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnLambda() As Task Dim markup = <a><![CDATA[ Imports System Class C Sub Goo() Dim obj = [|new Action(Of Integer, Integer)($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("Action(Of Integer, Integer)(Sub (Integer, Integer))", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Current Parameter Name" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCurrentParameterName() As Task Dim markup = <a><![CDATA[ Class C Sub New(int a, string b) End Sub Sub Goo() Dim obj = [|new C(b:=String.Empty, $$a:=2|]) End Sub End Class ]]></a>.Value Await VerifyCurrentParameterNameAsync(markup, "a") End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerParens() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2,$$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoInvocationOnSpace() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedCharacters() As Char = {","c, "("c} Dim unexpectedCharacters() As Char = {" "c, "["c, "<"c} VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer, y As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer, y As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function #End Region 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.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class ObjectCreationExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(ObjectCreationExpressionSignatureHelpProvider) End Function #Region "Regular tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickString() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:="Hello"$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickInteger() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:=1$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParametersMethodXmlComments() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo. See <see cref="System.Object"/> ''' </summary> Sub New() End Sub Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", "Summary for Goo. See Object", Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlCommentsOn1() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b</param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param a", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(545931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545931")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUnsupportedParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new String($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char())", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(c As Char, count As Integer)", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char(), startIndex As Integer, length As Integer)", currentParameterIndex:=0)) ' All the unsafe pointer overloads should be missing in VB Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlComentsOn2() As Task Dim markup = <a><![CDATA[ Imports System Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b. See <see cref="System.IAsyncResult"/></param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param b. See IAsyncResult", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParen() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParameters() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnLambda() As Task Dim markup = <a><![CDATA[ Imports System Class C Sub Goo() Dim obj = [|new Action(Of Integer, Integer)($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("Action(Of Integer, Integer)(Sub (Integer, Integer))", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Current Parameter Name" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCurrentParameterName() As Task Dim markup = <a><![CDATA[ Class C Sub New(int a, string b) End Sub Sub Goo() Dim obj = [|new C(b:=String.Empty, $$a:=2|]) End Sub End Class ]]></a>.Value Await VerifyCurrentParameterNameAsync(markup, "a") End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerParens() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2,$$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoInvocationOnSpace() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedCharacters() As Char = {","c, "("c} Dim unexpectedCharacters() As Char = {" "c, "["c, "<"c} VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer, y As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer, y As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/Core/Impl/xlf/SolutionExplorerShim.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="../SolutionExplorerShim.resx"> <body> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="Folder_Properties"> <source>Folder Properties</source> <target state="translated">フォルダーのプロパティ</target> <note /> </trans-unit> <trans-unit id="Analyzer_Properties"> <source>Analyzer Properties</source> <target state="translated">アナライザーのプロパティ</target> <note /> </trans-unit> <trans-unit id="Add_Analyzer"> <source>Add Analyzer</source> <target state="translated">アナライザーの追加</target> <note /> </trans-unit> <trans-unit id="Analyzer_Files"> <source>Analyzer Files</source> <target state="translated">アナライザー ファイル</target> <note /> </trans-unit> <trans-unit id="Diagnostic_Properties"> <source>Diagnostic Properties</source> <target state="translated">診断のプロパティ</target> <note /> </trans-unit> <trans-unit id="No_rule_set_file_is_specified_or_the_file_does_not_exist"> <source>No rule set file is specified, or the file does not exist.</source> <target state="translated">ルール セット ファイルが指定されていないか、ファイルが存在しません。</target> <note /> </trans-unit> <trans-unit id="Source_Generated_File_Properties"> <source>Source Generated File Properties</source> <target state="translated">ソースで生成されたファイルのプロパティ</target> <note /> </trans-unit> <trans-unit id="Source_Generator_Properties"> <source>Source Generator Properties</source> <target state="translated">ソース ジェネレーターのプロパティ</target> <note /> </trans-unit> <trans-unit id="The_rule_set_file_could_not_be_opened"> <source>The rule set file could not be opened.</source> <target state="translated">ルール セット ファイルを開くことができませんでした。</target> <note /> </trans-unit> <trans-unit id="The_rule_set_file_could_not_be_updated"> <source>The rule set file could not be updated.</source> <target state="translated">ルール セット ファイルを更新できませんでした。</target> <note /> </trans-unit> <trans-unit id="Could_not_create_a_rule_set_for_project_0"> <source>Could not create a rule set for project {0}.</source> <target state="translated">プロジェクト {0} にルール セットを作成できませんでした。</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">既定</target> <note /> </trans-unit> <trans-unit id="Error_"> <source>Error</source> <target state="translated">エラー</target> <note /> </trans-unit> <trans-unit id="This_generator_is_not_generating_files"> <source>This generator is not generating files.</source> <target state="translated">このジェネレーターではファイルは生成されていません。</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type Name</source> <target state="translated">型名</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> <trans-unit id="Info"> <source>Info</source> <target state="translated">情報</target> <note /> </trans-unit> <trans-unit id="Hidden"> <source>Hidden</source> <target state="translated">非表示</target> <note /> </trans-unit> <trans-unit id="Suppressed"> <source>Suppressed</source> <target state="translated">抑制済み</target> <note /> </trans-unit> <trans-unit id="Rule_Set"> <source>Rule Set</source> <target state="translated">ルール セット</target> <note /> </trans-unit> <trans-unit id="Checking_out_0_for_editing"> <source>Checking out {0} for editing...</source> <target state="translated">編集のために {0} をチェックアウトしています...</target> <note /> </trans-unit> <trans-unit id="Name"> <source>(Name)</source> <target state="translated">(名前)</target> <note /> </trans-unit> <trans-unit id="Path"> <source>Path</source> <target state="translated">パス</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">カテゴリ</target> <note /> </trans-unit> <trans-unit id="Default_severity"> <source>Default severity</source> <target state="translated">既定の重要度</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">説明</target> <note /> </trans-unit> <trans-unit id="Effective_severity"> <source>Effective severity</source> <target state="translated">有効な重要度</target> <note /> </trans-unit> <trans-unit id="Enabled_by_default"> <source>Enabled by default</source> <target state="translated">既定で有効化</target> <note /> </trans-unit> <trans-unit id="Help_link"> <source>Help link</source> <target state="translated">ヘルプ リンク</target> <note /> </trans-unit> <trans-unit id="ID"> <source>ID</source> <target state="translated">ID</target> <note /> </trans-unit> <trans-unit id="Message"> <source>Message</source> <target state="translated">メッセージ</target> <note /> </trans-unit> <trans-unit id="Tags"> <source>Tags</source> <target state="translated">タグ</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">タイトル</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="ja" original="../SolutionExplorerShim.resx"> <body> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">アナライザー</target> <note /> </trans-unit> <trans-unit id="Folder_Properties"> <source>Folder Properties</source> <target state="translated">フォルダーのプロパティ</target> <note /> </trans-unit> <trans-unit id="Analyzer_Properties"> <source>Analyzer Properties</source> <target state="translated">アナライザーのプロパティ</target> <note /> </trans-unit> <trans-unit id="Add_Analyzer"> <source>Add Analyzer</source> <target state="translated">アナライザーの追加</target> <note /> </trans-unit> <trans-unit id="Analyzer_Files"> <source>Analyzer Files</source> <target state="translated">アナライザー ファイル</target> <note /> </trans-unit> <trans-unit id="Diagnostic_Properties"> <source>Diagnostic Properties</source> <target state="translated">診断のプロパティ</target> <note /> </trans-unit> <trans-unit id="No_rule_set_file_is_specified_or_the_file_does_not_exist"> <source>No rule set file is specified, or the file does not exist.</source> <target state="translated">ルール セット ファイルが指定されていないか、ファイルが存在しません。</target> <note /> </trans-unit> <trans-unit id="Source_Generated_File_Properties"> <source>Source Generated File Properties</source> <target state="translated">ソースで生成されたファイルのプロパティ</target> <note /> </trans-unit> <trans-unit id="Source_Generator_Properties"> <source>Source Generator Properties</source> <target state="translated">ソース ジェネレーターのプロパティ</target> <note /> </trans-unit> <trans-unit id="The_rule_set_file_could_not_be_opened"> <source>The rule set file could not be opened.</source> <target state="translated">ルール セット ファイルを開くことができませんでした。</target> <note /> </trans-unit> <trans-unit id="The_rule_set_file_could_not_be_updated"> <source>The rule set file could not be updated.</source> <target state="translated">ルール セット ファイルを更新できませんでした。</target> <note /> </trans-unit> <trans-unit id="Could_not_create_a_rule_set_for_project_0"> <source>Could not create a rule set for project {0}.</source> <target state="translated">プロジェクト {0} にルール セットを作成できませんでした。</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">既定</target> <note /> </trans-unit> <trans-unit id="Error_"> <source>Error</source> <target state="translated">エラー</target> <note /> </trans-unit> <trans-unit id="This_generator_is_not_generating_files"> <source>This generator is not generating files.</source> <target state="translated">このジェネレーターではファイルは生成されていません。</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type Name</source> <target state="translated">型名</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> <trans-unit id="Info"> <source>Info</source> <target state="translated">情報</target> <note /> </trans-unit> <trans-unit id="Hidden"> <source>Hidden</source> <target state="translated">非表示</target> <note /> </trans-unit> <trans-unit id="Suppressed"> <source>Suppressed</source> <target state="translated">抑制済み</target> <note /> </trans-unit> <trans-unit id="Rule_Set"> <source>Rule Set</source> <target state="translated">ルール セット</target> <note /> </trans-unit> <trans-unit id="Checking_out_0_for_editing"> <source>Checking out {0} for editing...</source> <target state="translated">編集のために {0} をチェックアウトしています...</target> <note /> </trans-unit> <trans-unit id="Name"> <source>(Name)</source> <target state="translated">(名前)</target> <note /> </trans-unit> <trans-unit id="Path"> <source>Path</source> <target state="translated">パス</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">カテゴリ</target> <note /> </trans-unit> <trans-unit id="Default_severity"> <source>Default severity</source> <target state="translated">既定の重要度</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">説明</target> <note /> </trans-unit> <trans-unit id="Effective_severity"> <source>Effective severity</source> <target state="translated">有効な重要度</target> <note /> </trans-unit> <trans-unit id="Enabled_by_default"> <source>Enabled by default</source> <target state="translated">既定で有効化</target> <note /> </trans-unit> <trans-unit id="Help_link"> <source>Help link</source> <target state="translated">ヘルプ リンク</target> <note /> </trans-unit> <trans-unit id="ID"> <source>ID</source> <target state="translated">ID</target> <note /> </trans-unit> <trans-unit id="Message"> <source>Message</source> <target state="translated">メッセージ</target> <note /> </trans-unit> <trans-unit id="Tags"> <source>Tags</source> <target state="translated">タグ</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">タイトル</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, refactoringResult.DocumentToExtractFrom, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, refactoringResult.DocumentToExtractFrom, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } return false; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Emit/BreakingChanges.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BreakingChanges : CSharpTestBase { [Fact, WorkItem(527050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527050")] [Trait("Feature", "Directives")] public void TestCS1024DefineWithUnicodeInMiddle() { var test = @"#de\u0066in\U00000065 ABC"; // This is now a negative test, this should not be allowed. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_PPDirectiveExpected, @"de\u0066in\U00000065")); } [Fact, WorkItem(527951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527951")] public void CS0133ERR_NotConstantExpression05() { var text = @" class A { public void Do() { const object o1 = null; const string o2 = (string)o1; // Dev10 reports CS0133 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,22): warning CS0219: The variable 'o2' is assigned but its value is never used // const string o2 = (string)o1; // Dev10 reports CS0133 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o2").WithArguments("o2") ); } [WorkItem(527943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527943")] [Fact] public void CS0146ERR_CircularBase05() { var text = @" interface IFace<T> { } class B : IFace<B.C.D> { public class C { public class D { } } } "; var comp = CreateCompilation(text); // In Dev10, there was an error - ErrorCode.ERR_CircularBase at (4,7) Assert.Equal(0, comp.GetDiagnostics().Count()); } [WorkItem(540371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540371"), WorkItem(530792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530792")] [Fact] private void CS0507ERR_CantChangeAccessOnOverride_TestSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { protected internal get { return null; } set { } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; public class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics(); // This is not a breaking change - but it is a change in behavior from Dev10 // Dev10 used to report following errors - // Error CS0507: 'Derived.Property1.set': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property1.set' // Error CS0507: 'Derived.Property2.get': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property2.get' // Roslyn makes this case work by synthesizing 'protected' accessors for the missing ones var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseProperty1 = baseClass.GetMember<PropertySymbol>("Property1"); var baseProperty2 = baseClass.GetMember<PropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, baseProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty1.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty2.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.SetMethod.DeclaredAccessibility); var derivedClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedProperty1 = derivedClass.GetMember<SourcePropertySymbol>("Property1"); var derivedProperty2 = derivedClass.GetMember<SourcePropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, derivedProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, derivedProperty1.GetMethod.DeclaredAccessibility); Assert.Null(derivedProperty1.SetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.DeclaredAccessibility); Assert.Null(derivedProperty2.GetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.SetMethod.DeclaredAccessibility); var derivedProperty1Synthesized = derivedProperty1.SynthesizedSealedAccessorOpt; var derivedProperty2Synthesized = derivedProperty2.SynthesizedSealedAccessorOpt; Assert.Equal(MethodKind.PropertySet, derivedProperty1Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty1Synthesized.DeclaredAccessibility); Assert.Equal(MethodKind.PropertyGet, derivedProperty2Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty2Synthesized.DeclaredAccessibility); } // Confirm that this error no longer exists [Fact] public void CS0609ERR_NameAttributeOnOverride() { var text = @" using System.Runtime.CompilerServices; public class idx { public virtual int this[int iPropIndex] { get { return 0; } set { } } } public class MonthDays : idx { [IndexerName(""MonthInfoIndexer"")] public override int this[int iPropIndex] { get { return 1; } set { } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("MonthDays").Indexers.Single(); Assert.Equal(Microsoft.CodeAnalysis.WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("MonthInfoIndexer", indexer.MetadataName); } [WorkItem(527116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527116")] [Fact] public void RegressWarningInSingleMultiLineMixedXml() { var text = @" /// <summary> /** This is the summary */ /// </summary> class Test { /** <summary> */ /// This is the summary1 /** </summary> */ public int Field = 0; /** <summary> */ /// This is the summary2 /// </summary> string Prop { get; set; } /// <summary> /** This is the summary3 * </summary> */ static int Main() { return new Test().Field; } } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Dev10 allows (no warning) // Roslyn gives Warning CS1570 - "XML Comment has badly formed XML..." Assert.Equal(8, tree.GetDiagnostics().Count()); } [Fact, WorkItem(527093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527093")] public void NoCS1570ForUndefinedXmlNamespace() { var text = @" /// <xml> xmlns:s=""uuid: BDC6E3F0-6DA3-11d1-A2A3 - 00AA00C14882""> /// <s:inventory> /// </s:inventory> /// </xml> class A { } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Native Warning CS1570 - "XML Comment has badly formed XML..." // Roslyn no Assert.Empty(tree.GetDiagnostics()); } [Fact, WorkItem(541345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541345")] public void CS0019_TestNullCoalesceWithNullOperandsErrors() { var source = @" class Program { static void Main() { // This is acceptable by the native compiler and treated as a non-constant null literal. // That violates the specification; we now correctly treat this as an error. object a = null ?? null; // The null coalescing operator never produces a compile-time constant even when // the arguments are constants. const object b = null ?? ""ABC""; const string c = ""DEF"" ?? null; const int d = (int?)null ?? 123; // It is legal, though pointless, to use null literals and constants in coalescing // expressions, provided you don't try to make the result a constant. These should // produce no errors: object z = null ?? ""GHI""; string y = ""JKL"" ?? null; int x = (int?)null ?? 456; } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"null ?? ""ABC""").WithArguments("b"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"""DEF"" ?? null").WithArguments("c"), Diagnostic(ErrorCode.ERR_NotConstantExpression, "(int?)null ?? 123").WithArguments("d")); } [Fact, WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676"), WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676")] private // CS0657WRN_AttributeLocationOnBadDeclaration_AfterAttrDeclOrDelegate void CS1730ERR_CantUseAttributeOnInvaildLocation() { var test = @"using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public int Name; public Goo(int sName) { Name = sName; } } public delegate void EventHandler(object sender, EventArgs e); [assembly: Goo(5)] public class Test { } "; // In Dev10, this is a warning CS0657 // Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type") SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [WorkItem(528711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528711")] [Fact] public void CS9259_StructLayoutCycle() { var text = @"struct S1<T> { S1<S1<T>>.S2 x; struct S2 { static T x; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0169: The field 'S1<T>.x' is never used // S1<S1<T>>.S2 x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(3, 18), // (6,18): warning CS0169: The field 'S1<T>.S2.x' is never used // static T x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.S2.x").WithLocation(6, 18) ); } [WorkItem(528094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528094")] [Fact] public void FormattingUnicodeNotPartOfId() { string source = @" // <Area> Lexical - Unicode Characters</Area> // <Title> // Compiler considers identifiers, which differ only in formatting-character, as different ones; // This is not actually correct behavior but for the time being this is what we expect //</Title> //<RelatedBugs>DDB:133151</RelatedBugs> // <Expects Status=Success></Expects> #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; // Dev10 print '0' CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(529000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529000")] [Fact] public void NoCS0121ForSwitchedParamNames_Dev10814222() { string source = @" using System; // Bug Dev10: 814222 resolved as Won't Fix class Test { static void Main() { Console.Write(Bar(x: 1, y: ""T0"")); // Dev10:CS0121 Test01.Main01(); } public static int Bar(int x, string y, params int[] z) { return 1; } public static int Bar(string y, int x) { return 0; } // Roslyn pick this one } class Test01 { public static int Bar<T>(int x, T y, params int[] z) { return 1; } public static int Bar<T>(string y, int x) { return 0; } // Roslyn pick this one public static int Goo<T>(int x, T y) { return 1; } public static int Goo<T>(string y, int x) { return 0; } // Roslyn pick this one public static int AbcDef<T>(int x, T y) { return 0; } // Roslyn pick this one public static int AbcDef<T>(string y, int x, params int[] z) { return 1; } public static void Main01() { Console.Write(Bar<string>(x: 1, y: ""T1"")); // Dev10:CS0121 Console.Write(Goo<string>(x: 1, y: ""T2"")); // Dev10:CS0121 Console.Write(AbcDef<string>(x: 1, y: ""T3"")); // Dev10:CS0121 } } "; CompileAndVerify(source, expectedOutput: "0000"); } [WorkItem(529001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529001")] [WorkItem(529002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529002")] [WorkItem(1067, "https://github.com/dotnet/roslyn/issues/1067")] [Fact] public void CS0185ERR_LockNeedsReference_RequireRefType() { var source = @" class C { void M<T, TClass, TStruct>() where TClass : class where TStruct : struct { lock (default(object)) ; lock (default(int)) ; // CS0185 lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) lock (default(TClass)) {} lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) lock (null) {} // new CS0185 - null is not an object type } } "; var standardCompilation = CreateCompilation(source); var strictCompilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()); standardCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15) ); strictCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (10,15): error CS0185: 'T' is not a reference type as required by the lock statement // lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(T)").WithArguments("T").WithLocation(10, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15), // (13,15): error CS0185: '<null>' is not a reference type as required by the lock statement // lock (null) {} // new CS0185 - null is not an object type Diagnostic(ErrorCode.ERR_LockNeedsReference, "null").WithArguments("<null>").WithLocation(13, 15) ); } [WorkItem(528972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528972")] [Fact] public void CS0121ERR_AmbigCall_Lambda1() { var text = @" using System; class A { static void Main() { Goo( delegate () { throw new Exception(); }); // both Dev10 & Roslyn no error Goo(x: () => { throw new Exception(); }); // Dev10: CS0121, Roslyn: no error } public static void Goo(Action x) { Console.WriteLine(1); } public static void Goo(Func<int> x) { Console.WriteLine(2); // Roslyn call this one } } "; // Dev11 FIXED this, no error anymore (So Not breaking Dev11) // Dev10 reports CS0121 because ExpressionBinder::WhichConversionIsBetter fails to unwrap // the NamedArgumentSpecification to find the UNBOUNDLAMBDA and, thus, never calls // WhichLambdaConversionIsBetter. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(529202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529202")] public void NoCS0029_ErrorOnZeroToEnumToTypeConversion() { string source = @" class Program { static void Main() { S s = 0; } } enum E { Zero, One, Two } struct S { public static implicit operator S(E s) { return E.Zero; } }"; // Dev10/11: (11,9): error CS0029: Cannot implicitly convert type 'int' to 'S' CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0029: Cannot implicitly convert type 'int' to 'S' // S s = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "S") ); } [Fact, WorkItem(529242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529242")] public void ThrowOverflowExceptionForUncheckedCheckedLambda() { string source = @" using System; class Program { static void Main() { Func<int, int> d = checked(delegate(int i) { int max = int.MaxValue; try { int n = max + 1; } catch (OverflowException) { Console.Write(""OV ""); // Roslyn throw } return i; }); var r = unchecked(d(9)); Console.Write(r); } } "; CompileAndVerify(source, expectedOutput: "OV 9"); } [WorkItem(529262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529262")] [Fact] public void PartialMethod_ParameterAndTypeParameterNames() { var source = @"using System; using System.Reflection; partial class C { static partial void M<T, U>(T x, U y); static partial void M<T1, T2>(T1 y, T2 x) { Console.Write(""{0}, {1} | "", x, y); var m = typeof(C).GetMethod(""M"", BindingFlags.Static | BindingFlags.NonPublic); var tp = m.GetGenericArguments(); Console.Write(""{0}, {1} | "", tp[0].Name, tp[1].Name); var p = m.GetParameters(); Console.Write(""{0}, {1}"", p[0].Name, p[1].Name); } static void Main() { M(x: 1, y: 2); } }"; // Dev12 would emit "2, 1 | T1, T2 | x, y". CompileAndVerify(source, expectedOutput: "2, 1 | T, U | x, y"); } [Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")] public void NewCS0029_ImplicitlyUnwrapGenericNullable() { string source = @" public class GenC<T, U> where T : struct, U { public void Test(T t) { /*<bind>*/T? nt = t;/*</bind>*/ U valueUn = nt; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS0029: Cannot implicitly convert type 'T?' to 'U' // U valueUn = nt; Diagnostic(ErrorCode.ERR_NoImplicitConv, "nt").WithArguments("T?", "U")); VerifyOperationTreeForTest<LocalDeclarationStatementSyntax>(comp, @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'T? nt = t;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'T? nt = t') Declarators: IVariableDeclaratorOperation (Symbol: T? nt) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'nt = t') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= t') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: T?, IsImplicit) (Syntax: 't') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') Initializer: null "); } [Fact, WorkItem(529280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529280"), WorkItem(546864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546864")] public void ExplicitUDCWithGenericConstraints() { // This compiles successfully in Dev10 dues to a bug; a user-defined conversion // that converts from or to an interface should never be chosen. If you are // converting from Alpha to Beta via standard conversion, then Beta to Gamma // via user-defined conversion, then Gamma to Delta via standard conversion, then // none of Alpha, Beta, Gamma or Delta should be allowed to be interfaces. The // Dev10 compiler only checks Alpha and Delta, not Beta and Gamma. // // Unfortunately, real-world code both in devdiv and in the wild depends on this // behavior, so we are replicating the bug in Roslyn. string source = @"using System; public interface IGoo { void Method(); } public class CT : IGoo { public void Method() { } } public class GenC<T> where T : IGoo { public T valueT; public static explicit operator T(GenC<T> val) { Console.Write(""ExpConv""); return val.valueT; } } public class Test { public static void Main() { var _class = new GenC<IGoo>(); var ret = (CT)_class; } } "; // CompileAndVerify(source, expectedOutput: "ExpConv"); CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC() { string source = @"using System; struct GenS<T> where T : struct { public static int Flag; public static explicit operator T?(GenS<T> s) { Flag = 3; return default(T); } public static implicit operator T(GenS<T> s) { Flag = 2; return default(T); } } class Program { public static void Main() { int? int_a1 = 1; GenS<int>? s28 = new GenS<int>(); // Due to related bug dev10: 742047 is won't fix // so expects the code will call explicit conversion operator int? result28 = s28 ?? int_a1; Console.WriteLine(GenS<int>.Flag); } } "; // Native compiler picks explicit conversion - print 3 CompileAndVerify(source, expectedOutput: "2"); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC_2() { string source = @"using System; struct S { public static explicit operator int?(S? s) { Console.WriteLine(""Explicit""); return 3; } public static implicit operator int(S? s) { Console.WriteLine(""Implicit""); return 2; } } class Program { public static void Main() { int? nn = -1; S? s = new S(); int? ret = s ?? nn; } } "; // Native compiler picks explicit conversion CompileAndVerify(source, expectedOutput: "Implicit"); } [Fact, WorkItem(529363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529363")] public void AssignmentNullCoalescingOperator() { string source = @"using System; class NullCoalescingTest { public static void Main() { int? a; int c; var x = (a = null) ?? (c = 123); Console.WriteLine(c); } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0165: Use of unassigned local variable 'c' // Console.WriteLine(c); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (7,14): warning CS0219: The variable 'a' is assigned but its value is never used // int? a; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a")); } [Fact, WorkItem(529464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529464")] public void MultiDimensionArrayWithDiffTypeIndexDevDiv31328() { var text = @" class A { public static void Main() { byte[,] arr = new byte[1, 1]; ulong i1 = 0; int i2 = 1; arr[i1, i2] = 127; // Dev10 CS0266 } } "; // Dev10 Won't fix bug#31328 for md array with different types' index and involving ulong // CS0266: Cannot implicitly convert type 'ulong' to 'int'. ... CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_SubtractNullLiteral() { var text = @" unsafe class C { long M(int* p) { return p - null; //Dev10 reports CS0019 } } "; // Dev10: the null literal is treated as though it is converted to void*, making the subtraction illegal (ExpressionBinder::GetPtrBinOpSigs). // Roslyn: the null literal is converted to int*, making the subtraction legal. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0181ERR_BadAttributeParamType_Nullable() { var text = @" [Boom] class Boom : System.Attribute { public Boom(int? x = 0) { } static void Main() { typeof(Boom).GetCustomAttributes(true); } } "; // Roslyn: error CS0181: Attribute constructor parameter 'x' has type 'int?', which is not a valid attribute parameter type // Dev10/11: no error, but throw at runtime - System.Reflection.CustomAttributeFormatException CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Boom").WithArguments("x", "int?")); } /// <summary> /// When determining whether the LHS of a null-coalescing operator (??) is non-null, the native compiler strips off casts. /// /// We have decided not to reproduce this behavior. /// </summary> [Fact] public void CastOnLhsOfConditionalOperator() { var text = @" class C { static void Main(string[] args) { int i; int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. int k; int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. int m; int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator } } "; // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // Dev10/11: no error CreateCompilation(text).VerifyDiagnostics( // This is new in Roslyn. // (7,29): error CS0165: Use of unassigned local variable 'i' // int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i"), // These match Dev10. // (10,36): error CS0165: Use of unassigned local variable 'k' // int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k"), // (13,57): error CS0165: Use of unassigned local variable 'm' // int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator Diagnostic(ErrorCode.ERR_UseDefViolation, "m").WithArguments("m")); } [WorkItem(529974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529974")] [Fact] public void TestCollisionForLoopControlVariable() { var source = @" namespace Microsoft.Test.XmlGen.Protocols.Saml2 { using System; using System.Collections.Generic; public class ProxyRestriction { XmlGenIntegerAttribute count; private List<XmlGenAttribute> Attributes { get; set; } public ProxyRestriction() { for (int count = 0; count < 10; count++) { } for (int i = 0; i < this.Attributes.Count; i++) { XmlGenAttribute attribute = this.Attributes[i]; if (attribute.LocalName == null) { if (count is XmlGenIntegerAttribute) { count = (XmlGenIntegerAttribute)attribute; } else { count = new XmlGenIntegerAttribute(attribute); this.Attributes[i] = count; } break; } } if (count == null) { this.Attributes.Add(new XmlGenIntegerAttribute(String.Empty, null, String.Empty, -1, false)); } } } internal class XmlGenAttribute { public object LocalName { get; internal set; } } internal class XmlGenIntegerAttribute : XmlGenAttribute { public XmlGenIntegerAttribute(string empty1, object count, string empty2, int v, bool isPresent) { } public XmlGenIntegerAttribute(XmlGenAttribute attribute) { } } } public class Program { public static void Main() { } }"; // Dev11 reported no errors for the above repro and allowed the name 'count' to bind to different // variables within the same declaration space. According to the old spec the error should be reported. // In Roslyn the single definition rule is relaxed and we do not give an error, but for a different reason. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530301")] public void NoMore_CS0458WRN_AlwaysNull02() { CreateCompilation( @" public class Test { const bool ct = true; public static int Main() { var a = (true & null) ?? null; // CS0458 if (((null & true) == null)) // CS0458 return 0; var b = !(null | false); // CS0458 if ((false | null) != null) // CS0458 return 1; const bool cf = false; var d = ct & null ^ null; // CS0458 - Roslyn Warn this ONLY d ^= !(null | cf); // CS0458 return -1; } } ") // We decided to not report WRN_AlwaysNull in some cases. .VerifyDiagnostics( // Diagnostic(ErrorCode.WRN_AlwaysNull, "true & null").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null & true").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | false").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "false | null").WithArguments("bool?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "ct & null ^ null").WithArguments("bool?") //, // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | cf").WithArguments("bool?") ); } [WorkItem(530403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530403")] [Fact] public void CS0135_local_param_cannot_be_declared() { // Dev11 missed this error. The issue is that an a is a field of c, and then it is a local in parts of d. // by then referring to the field without the this keyword, it should be flagged as declaring a competing variable (as it is confusing). var text = @" using System; public class c { int a = 0; void d(bool b) { if(b) { int a = 1; Console.WriteLine(a); } else { a = 2; } a = 3; Console.WriteLine(a); } } "; var comp = CreateCompilation(text); // In Roslyn the single definition rule is relaxed and we do not give an error. comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] [WorkItem(530518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530518")] public void ExpressionTreeExplicitOpVsConvert() { var text = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static explicit operator int(Test x) { return 1; } static void Main() { Expression<Func<Test, long?>> testExpr1 = x => (long?)x; Console.WriteLine(testExpr1); Expression<Func<Test, decimal?>> testExpr2 = x => (decimal?)x; Console.WriteLine(testExpr2); } } "; // Native Compiler: x => Convert(Convert(op_Explicit(x))) CompileAndVerify(text, expectedOutput: @"x => Convert(Convert(Convert(x))) x => Convert(Convert(Convert(x))) "); } [WorkItem(530531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530531")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] private void ExpressionTreeNoCovertForIdentityConversion() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { static void Main() { Expression<Func<Guid, bool>> e = (x) => x != null; Console.WriteLine(e); Console.WriteLine(e.Compile()(default(Guid))); } } "; // Native compiler: x => (Convert(x) != Convert(null)) CompileAndVerify(source, expectedOutput: @"x => (Convert(x) != null) True "); } [Fact, WorkItem(530548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530548")] public void CS0219WRN_UnreferencedVarAssg_RHSMidRefType() { string source = @" public interface Base { } public struct Derived : Base { } public class Test { public static void Main() { var b1 = new Derived(); // Both Warning CS0219 var b2 = (Base)new Derived(); // Both NO Warn (reference type) var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'b1' is assigned but its value is never used // var b1 = new Derived(); // Both Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1"), // (10,13): warning CS0219: The variable 'b3' is assigned but its value is never used // var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b3").WithArguments("b3")); } [Fact, WorkItem(530556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530556")] public void NoCS0591ERR_InvalidAttributeArgument() { string source = @" using System; [AttributeUsage(AttributeTargets.All + 0xFFFFFF)] class MyAtt : Attribute { } [AttributeUsage((AttributeTargets)0xffff)] class MyAtt1 : Attribute { } public class Test {} "; // Native compiler error CS0591: Invalid value for argument to 'AttributeUsage' attribute CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530586")] public void ThrowOnceInIteratorFinallyBlock() { string source = @" //<Title> Finally block runs twice in iterator</Title> //<RelatedBug>Dev10:473561-->8444?</RelatedBug> using System; using System.Collections; class Program { public static void Main() { var demo = new test(); try { foreach (var x in demo.Goo()) { } } catch (Exception) { Console.Write(""EX ""); } Console.WriteLine(demo.count); } class test { public int count = 0; public IEnumerable Goo() { try { yield return null; try { yield break; } catch { } } finally { Console.Write(""++ ""); ++count; throw new Exception(); } } } } "; // Native print "++ ++ EX 2" var verifier = CompileAndVerify(source, expectedOutput: " ++ EX 1"); // must not load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 101 (0x65) .maxstack 2 .locals init (bool V_0, int V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: brfalse.s IL_0012 IL_000a: ldloc.1 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0033 IL_000e: ldc.i4.0 IL_000f: stloc.0 IL_0010: leave.s IL_0063 IL_0012: ldarg.0 IL_0013: ldc.i4.m1 IL_0014: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0019: ldarg.0 IL_001a: ldc.i4.s -3 IL_001c: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Program.test.<Goo>d__1.<>2__current"" IL_0028: ldarg.0 IL_0029: ldc.i4.1 IL_002a: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_002f: ldc.i4.1 IL_0030: stloc.0 IL_0031: leave.s IL_0063 IL_0033: ldarg.0 IL_0034: ldc.i4.s -3 IL_0036: stfld ""int Program.test.<Goo>d__1.<>1__state"" .try { IL_003b: ldc.i4.0 IL_003c: stloc.0 IL_003d: leave.s IL_004a } catch object { IL_003f: pop IL_0040: leave.s IL_0042 } IL_0042: ldarg.0 IL_0043: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0048: br.s IL_0052 IL_004a: ldarg.0 IL_004b: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0050: leave.s IL_0063 IL_0052: leave.s IL_005b } fault { IL_0054: ldarg.0 IL_0055: call ""void Program.test.<Goo>d__1.Dispose()"" IL_005a: endfinally } IL_005b: ldarg.0 IL_005c: call ""void Program.test.<Goo>d__1.Dispose()"" IL_0061: ldc.i4.1 IL_0062: stloc.0 IL_0063: ldloc.0 IL_0064: ret } "); // must load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.<>m__Finally1()", @" { // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.m1 IL_0002: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0007: ldarg.0 IL_0008: ldfld ""Program.test Program.test.<Goo>d__1.<>4__this"" IL_000d: ldstr ""++ "" IL_0012: call ""void System.Console.Write(string)"" IL_0017: dup IL_0018: ldfld ""int Program.test.count"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stfld ""int Program.test.count"" IL_0024: newobj ""System.Exception..ctor()"" IL_0029: throw } "); } [Fact, WorkItem(530587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530587")] public void NoFormatCharInIDEqual() { string source = @" #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; CompileAndVerify(source, expectedOutput: "1"); // Native print 0 } [Fact, WorkItem(530614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530614")] public void CS1718WRN_ComparisonToSelf_Roslyn() { string source = @" enum esbyte : sbyte { e0, e1 }; public class z_1495j12 { public static void Main() { if (esbyte.e0 == esbyte.e0) { System.Console.WriteLine(""T""); } }} "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (7,5): warning CS1718: Comparison made to same variable; did you mean to compare something else? Diagnostic(ErrorCode.WRN_ComparisonToSelf, "esbyte.e0 == esbyte.e0")); } [Fact, WorkItem(530629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530629")] public void CS0414WRN_UnreferencedFieldAssg_Roslyn() { string source = @" namespace VS7_336319 { public sealed class PredefinedTypes { public class Kind { public static int Decimal; } } public class ExpressionBinder { private static PredefinedTypes PredefinedTypes = null; private void Goo() { if (0 == (int)PredefinedTypes.Kind.Decimal) { } } } } "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (10,40): warning CS0414: The field 'VS7_336319.ExpressionBinder.PredefinedTypes' is assigned but its value is never used // private static PredefinedTypes PredefinedTypes = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "PredefinedTypes").WithArguments("VS7_336319.ExpressionBinder.PredefinedTypes")); } [WorkItem(530666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530666")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] public void ExpressionTreeWithNullableUDCandOperator() { string source = @" using System; using System.Linq.Expressions; struct B { public static implicit operator int?(B x) { return 1; } public static int operator +(B x, int y) { return 2 + y; } static int Main() { Expression<Func<B, int?>> f = x => x + x; var ret = f.Compile()(new B()); Console.WriteLine(ret); return ret.Value - 3; } } "; // Native compiler throw CompileAndVerify(source, expectedOutput: "3"); } [Fact, WorkItem(530696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530696")] public void CS0121Err_AmbiguousMethodCall() { string source = @" class G<T> { } class C { static void M(params double[] x) { System.Console.WriteLine(1); } static void M(params G<int>[] x) { System.Console.WriteLine(2); } static void Main() { M(); } } "; CreateCompilation(source).VerifyDiagnostics( // (15,13): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params double[])' and 'C.M(params G<int>[])' // M(); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params double[])", "C.M(params G<int>[])")); } [Fact, WorkItem(530653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530653")] public void RepeatedObsoleteWarnings() { // <quote source="Srivatsn's comments from bug 16642"> // Inside a method body if you access a static field twice thus: // // var x = ObsoleteType.field1; // var y = ObsoleteType.field1; // // then the native compiler reports ObsoleteType as obsolete only once. This is because the native compiler caches // the lookup of type names for certain cases and doesn't report errors on the second lookup as that just comes // from the cache. Note how I said caches sometimes. If you simply say - // // var x= new ObsoleteType(); // var y = new ObsoleteType(); // // Then the native compiler reports the error twice. I don't think we should replicate this in Roslyn. Note however // that this is a breaking change because if the first line had been #pragma disabled, then the code would compile // without warnings in Dev11 but we will report warnings. I think it's a corner enough scenario and the native // behavior is quirky enough to warrant a break. // </quote> CompileAndVerify(@" using System; [Obsolete] public class ObsoleteType { public static readonly int field = 0; } public class Program { public static void Main() { #pragma warning disable 0612 var x = ObsoleteType.field; #pragma warning restore 0612 var y = ObsoleteType.field; // In Dev11, this line doesn't produce a warning. } }").VerifyDiagnostics( // (15,17): warning CS0612: 'ObsoleteType' is obsolete // var y = ObsoleteType.field; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "ObsoleteType").WithArguments("ObsoleteType")); } [Fact, WorkItem(530303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530303")] public void TestReferenceResolution() { var cs1Compilation = CreateCSharpCompilation("CS1", @"public class CS1 {}", compilationOptions: TestOptions.ReleaseDll); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"public class CS2<T> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation); cs2Verifier.VerifyDiagnostics(); var cs3Compilation = CreateCSharpCompilation("CS3", @"public class CS3 : CS2<CS1> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation, cs2Compilation }); var cs3Verifier = CompileAndVerify(cs3Compilation); cs3Verifier.VerifyDiagnostics(); var cs4Compilation = CreateCSharpCompilation("CS4", @"public class Program { static void Main() { System.Console.WriteLine(typeof(CS3)); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { cs2Compilation, cs3Compilation }); cs4Compilation.VerifyDiagnostics(); } [Fact, WorkItem(531014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531014")] public void TestVariableAndTypeNameClashes() { CompileAndVerify(@" using System; public class Class1 { internal class A4 { internal class B { } internal static string F() { return ""A4""; } } internal class A5 { internal class B { } internal static string F() { return ""A5""; } } internal class A6 { internal class B { } internal static string F() { return ""A6""; } } internal delegate void D(); // Check the weird E.M cases. internal class Outer2 { internal static void F(A4 A4) { A5 A5; const A6 A6 = null; Console.WriteLine(typeof(A4.B)); Console.WriteLine(typeof(A5.B)); Console.WriteLine(typeof(A6.B)); Console.WriteLine(A4.F()); Console.WriteLine(A5.F()); Console.WriteLine(A6.F()); Console.WriteLine(default(A4) == null); Console.WriteLine(default(A5) == null); Console.WriteLine(default(A6) == null); } } }").VerifyDiagnostics( // Breaking Change: See bug 17395. Dev11 had a bug because of which it didn't report the below warnings. // (13,16): warning CS0168: The variable 'A5' is declared but never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "A5").WithArguments("A5"), // (13,29): warning CS0219: The variable 'A6' is assigned but its value is never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "A6").WithArguments("A6")); } [WorkItem(530584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530584")] [Fact] public void NotRuntimeAmbiguousBecauseOfReturnTypes() { var source = @" using System; class Base<T, S> { public virtual int Goo(ref S x) { return 0; } public virtual string Goo(out T x) { x = default(T); return ""Base.Out""; } } class Derived : Base<int, int> { public override string Goo(out int x) { x = 0; return ""Derived.Out""; } static void Main() { int x; Console.WriteLine(new Derived().Goo(out x)); } } "; // BREAK: Dev11 reports WRN_MultipleRuntimeOverrideMatches, but there // is no runtime ambiguity because the return types differ. CompileAndVerify(source, expectedOutput: "Derived.Out"); } [WorkItem(695311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695311")] [Fact] public void NestedCollectionInitializerOnGenericProperty() { var libSource = @" using System.Collections; public interface IAdd { void Add(object o); } public struct S : IEnumerable, IAdd { private ArrayList list; public void Add(object o) { list = list ?? new ArrayList(); list.Add(o); } public IEnumerator GetEnumerator() { return (list ?? new ArrayList()).GetEnumerator(); } } public class C : IEnumerable, IAdd { private readonly ArrayList list = new ArrayList(); public void Add(object o) { list.Add(o); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } } public class Wrapper<T> : IEnumerable where T : IEnumerable, new() { public Wrapper() { this.Item = new T(); } public T Item { get; private set; } public IEnumerator GetEnumerator() { return Item.GetEnumerator(); } } public static class Util { public static int Count(IEnumerable i) { int count = 0; foreach (var v in i) count++; return count; } } "; var libRef = CreateCompilation(libSource, assemblyName: "lib").EmitToImageReference(); { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "03"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : class, IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. // NOTE: The spec will likely be updated to make this illegal. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "3"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); } static Wrapper<T> Goo<T>() where T : struct, IEnumerable, IAdd { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // BREAK: dev11 compiles and prints "0" var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (15,33): error CS1918: Members of property 'Wrapper<T>.Item' of type 'T' cannot be assigned with an object initializer because it is of a value type // return new Wrapper<T> { Item = { 1, 2, 3} }; Diagnostic(ErrorCode.ERR_ValueTypePropertyInObjectInitializer, "Item").WithArguments("Wrapper<T>.Item", "T")); } } [Fact, WorkItem(770424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770424"), WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")] public void UserDefinedShortCircuitingOperators() { var source = @" public class Base { public static bool operator true(Base x) { System.Console.Write(""Base.op_True""); return x != null; } public static bool operator false(Base x) { System.Console.Write(""Base.op_False""); return x == null; } } public class Derived : Base { public static Derived operator&(Derived x, Derived y) { return x; } public static Derived operator|(Derived x, Derived y) { return y; } static void Main() { Derived d = new Derived(); var b = (d && d) || d; } } "; CompileAndVerify(source, expectedOutput: "Base.op_FalseBase.op_True"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; 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 { public class BreakingChanges : CSharpTestBase { [Fact, WorkItem(527050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527050")] [Trait("Feature", "Directives")] public void TestCS1024DefineWithUnicodeInMiddle() { var test = @"#de\u0066in\U00000065 ABC"; // This is now a negative test, this should not be allowed. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_PPDirectiveExpected, @"de\u0066in\U00000065")); } [Fact, WorkItem(527951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527951")] public void CS0133ERR_NotConstantExpression05() { var text = @" class A { public void Do() { const object o1 = null; const string o2 = (string)o1; // Dev10 reports CS0133 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,22): warning CS0219: The variable 'o2' is assigned but its value is never used // const string o2 = (string)o1; // Dev10 reports CS0133 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o2").WithArguments("o2") ); } [WorkItem(527943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527943")] [Fact] public void CS0146ERR_CircularBase05() { var text = @" interface IFace<T> { } class B : IFace<B.C.D> { public class C { public class D { } } } "; var comp = CreateCompilation(text); // In Dev10, there was an error - ErrorCode.ERR_CircularBase at (4,7) Assert.Equal(0, comp.GetDiagnostics().Count()); } [WorkItem(540371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540371"), WorkItem(530792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530792")] [Fact] private void CS0507ERR_CantChangeAccessOnOverride_TestSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { protected internal get { return null; } set { } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; public class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics(); // This is not a breaking change - but it is a change in behavior from Dev10 // Dev10 used to report following errors - // Error CS0507: 'Derived.Property1.set': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property1.set' // Error CS0507: 'Derived.Property2.get': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property2.get' // Roslyn makes this case work by synthesizing 'protected' accessors for the missing ones var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseProperty1 = baseClass.GetMember<PropertySymbol>("Property1"); var baseProperty2 = baseClass.GetMember<PropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, baseProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty1.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty2.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.SetMethod.DeclaredAccessibility); var derivedClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedProperty1 = derivedClass.GetMember<SourcePropertySymbol>("Property1"); var derivedProperty2 = derivedClass.GetMember<SourcePropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, derivedProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, derivedProperty1.GetMethod.DeclaredAccessibility); Assert.Null(derivedProperty1.SetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.DeclaredAccessibility); Assert.Null(derivedProperty2.GetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.SetMethod.DeclaredAccessibility); var derivedProperty1Synthesized = derivedProperty1.SynthesizedSealedAccessorOpt; var derivedProperty2Synthesized = derivedProperty2.SynthesizedSealedAccessorOpt; Assert.Equal(MethodKind.PropertySet, derivedProperty1Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty1Synthesized.DeclaredAccessibility); Assert.Equal(MethodKind.PropertyGet, derivedProperty2Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty2Synthesized.DeclaredAccessibility); } // Confirm that this error no longer exists [Fact] public void CS0609ERR_NameAttributeOnOverride() { var text = @" using System.Runtime.CompilerServices; public class idx { public virtual int this[int iPropIndex] { get { return 0; } set { } } } public class MonthDays : idx { [IndexerName(""MonthInfoIndexer"")] public override int this[int iPropIndex] { get { return 1; } set { } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("MonthDays").Indexers.Single(); Assert.Equal(Microsoft.CodeAnalysis.WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("MonthInfoIndexer", indexer.MetadataName); } [WorkItem(527116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527116")] [Fact] public void RegressWarningInSingleMultiLineMixedXml() { var text = @" /// <summary> /** This is the summary */ /// </summary> class Test { /** <summary> */ /// This is the summary1 /** </summary> */ public int Field = 0; /** <summary> */ /// This is the summary2 /// </summary> string Prop { get; set; } /// <summary> /** This is the summary3 * </summary> */ static int Main() { return new Test().Field; } } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Dev10 allows (no warning) // Roslyn gives Warning CS1570 - "XML Comment has badly formed XML..." Assert.Equal(8, tree.GetDiagnostics().Count()); } [Fact, WorkItem(527093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527093")] public void NoCS1570ForUndefinedXmlNamespace() { var text = @" /// <xml> xmlns:s=""uuid: BDC6E3F0-6DA3-11d1-A2A3 - 00AA00C14882""> /// <s:inventory> /// </s:inventory> /// </xml> class A { } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Native Warning CS1570 - "XML Comment has badly formed XML..." // Roslyn no Assert.Empty(tree.GetDiagnostics()); } [Fact, WorkItem(541345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541345")] public void CS0019_TestNullCoalesceWithNullOperandsErrors() { var source = @" class Program { static void Main() { // This is acceptable by the native compiler and treated as a non-constant null literal. // That violates the specification; we now correctly treat this as an error. object a = null ?? null; // The null coalescing operator never produces a compile-time constant even when // the arguments are constants. const object b = null ?? ""ABC""; const string c = ""DEF"" ?? null; const int d = (int?)null ?? 123; // It is legal, though pointless, to use null literals and constants in coalescing // expressions, provided you don't try to make the result a constant. These should // produce no errors: object z = null ?? ""GHI""; string y = ""JKL"" ?? null; int x = (int?)null ?? 456; } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"null ?? ""ABC""").WithArguments("b"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"""DEF"" ?? null").WithArguments("c"), Diagnostic(ErrorCode.ERR_NotConstantExpression, "(int?)null ?? 123").WithArguments("d")); } [Fact, WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676"), WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676")] private // CS0657WRN_AttributeLocationOnBadDeclaration_AfterAttrDeclOrDelegate void CS1730ERR_CantUseAttributeOnInvaildLocation() { var test = @"using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public int Name; public Goo(int sName) { Name = sName; } } public delegate void EventHandler(object sender, EventArgs e); [assembly: Goo(5)] public class Test { } "; // In Dev10, this is a warning CS0657 // Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type") SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [WorkItem(528711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528711")] [Fact] public void CS9259_StructLayoutCycle() { var text = @"struct S1<T> { S1<S1<T>>.S2 x; struct S2 { static T x; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0169: The field 'S1<T>.x' is never used // S1<S1<T>>.S2 x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(3, 18), // (6,18): warning CS0169: The field 'S1<T>.S2.x' is never used // static T x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.S2.x").WithLocation(6, 18) ); } [WorkItem(528094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528094")] [Fact] public void FormattingUnicodeNotPartOfId() { string source = @" // <Area> Lexical - Unicode Characters</Area> // <Title> // Compiler considers identifiers, which differ only in formatting-character, as different ones; // This is not actually correct behavior but for the time being this is what we expect //</Title> //<RelatedBugs>DDB:133151</RelatedBugs> // <Expects Status=Success></Expects> #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; // Dev10 print '0' CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(529000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529000")] [Fact] public void NoCS0121ForSwitchedParamNames_Dev10814222() { string source = @" using System; // Bug Dev10: 814222 resolved as Won't Fix class Test { static void Main() { Console.Write(Bar(x: 1, y: ""T0"")); // Dev10:CS0121 Test01.Main01(); } public static int Bar(int x, string y, params int[] z) { return 1; } public static int Bar(string y, int x) { return 0; } // Roslyn pick this one } class Test01 { public static int Bar<T>(int x, T y, params int[] z) { return 1; } public static int Bar<T>(string y, int x) { return 0; } // Roslyn pick this one public static int Goo<T>(int x, T y) { return 1; } public static int Goo<T>(string y, int x) { return 0; } // Roslyn pick this one public static int AbcDef<T>(int x, T y) { return 0; } // Roslyn pick this one public static int AbcDef<T>(string y, int x, params int[] z) { return 1; } public static void Main01() { Console.Write(Bar<string>(x: 1, y: ""T1"")); // Dev10:CS0121 Console.Write(Goo<string>(x: 1, y: ""T2"")); // Dev10:CS0121 Console.Write(AbcDef<string>(x: 1, y: ""T3"")); // Dev10:CS0121 } } "; CompileAndVerify(source, expectedOutput: "0000"); } [WorkItem(529001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529001")] [WorkItem(529002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529002")] [WorkItem(1067, "https://github.com/dotnet/roslyn/issues/1067")] [Fact] public void CS0185ERR_LockNeedsReference_RequireRefType() { var source = @" class C { void M<T, TClass, TStruct>() where TClass : class where TStruct : struct { lock (default(object)) ; lock (default(int)) ; // CS0185 lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) lock (default(TClass)) {} lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) lock (null) {} // new CS0185 - null is not an object type } } "; var standardCompilation = CreateCompilation(source); var strictCompilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()); standardCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15) ); strictCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (10,15): error CS0185: 'T' is not a reference type as required by the lock statement // lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(T)").WithArguments("T").WithLocation(10, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15), // (13,15): error CS0185: '<null>' is not a reference type as required by the lock statement // lock (null) {} // new CS0185 - null is not an object type Diagnostic(ErrorCode.ERR_LockNeedsReference, "null").WithArguments("<null>").WithLocation(13, 15) ); } [WorkItem(528972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528972")] [Fact] public void CS0121ERR_AmbigCall_Lambda1() { var text = @" using System; class A { static void Main() { Goo( delegate () { throw new Exception(); }); // both Dev10 & Roslyn no error Goo(x: () => { throw new Exception(); }); // Dev10: CS0121, Roslyn: no error } public static void Goo(Action x) { Console.WriteLine(1); } public static void Goo(Func<int> x) { Console.WriteLine(2); // Roslyn call this one } } "; // Dev11 FIXED this, no error anymore (So Not breaking Dev11) // Dev10 reports CS0121 because ExpressionBinder::WhichConversionIsBetter fails to unwrap // the NamedArgumentSpecification to find the UNBOUNDLAMBDA and, thus, never calls // WhichLambdaConversionIsBetter. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(529202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529202")] public void NoCS0029_ErrorOnZeroToEnumToTypeConversion() { string source = @" class Program { static void Main() { S s = 0; } } enum E { Zero, One, Two } struct S { public static implicit operator S(E s) { return E.Zero; } }"; // Dev10/11: (11,9): error CS0029: Cannot implicitly convert type 'int' to 'S' CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0029: Cannot implicitly convert type 'int' to 'S' // S s = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "S") ); } [Fact, WorkItem(529242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529242")] public void ThrowOverflowExceptionForUncheckedCheckedLambda() { string source = @" using System; class Program { static void Main() { Func<int, int> d = checked(delegate(int i) { int max = int.MaxValue; try { int n = max + 1; } catch (OverflowException) { Console.Write(""OV ""); // Roslyn throw } return i; }); var r = unchecked(d(9)); Console.Write(r); } } "; CompileAndVerify(source, expectedOutput: "OV 9"); } [WorkItem(529262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529262")] [Fact] public void PartialMethod_ParameterAndTypeParameterNames() { var source = @"using System; using System.Reflection; partial class C { static partial void M<T, U>(T x, U y); static partial void M<T1, T2>(T1 y, T2 x) { Console.Write(""{0}, {1} | "", x, y); var m = typeof(C).GetMethod(""M"", BindingFlags.Static | BindingFlags.NonPublic); var tp = m.GetGenericArguments(); Console.Write(""{0}, {1} | "", tp[0].Name, tp[1].Name); var p = m.GetParameters(); Console.Write(""{0}, {1}"", p[0].Name, p[1].Name); } static void Main() { M(x: 1, y: 2); } }"; // Dev12 would emit "2, 1 | T1, T2 | x, y". CompileAndVerify(source, expectedOutput: "2, 1 | T, U | x, y"); } [Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")] public void NewCS0029_ImplicitlyUnwrapGenericNullable() { string source = @" public class GenC<T, U> where T : struct, U { public void Test(T t) { /*<bind>*/T? nt = t;/*</bind>*/ U valueUn = nt; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS0029: Cannot implicitly convert type 'T?' to 'U' // U valueUn = nt; Diagnostic(ErrorCode.ERR_NoImplicitConv, "nt").WithArguments("T?", "U")); VerifyOperationTreeForTest<LocalDeclarationStatementSyntax>(comp, @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'T? nt = t;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'T? nt = t') Declarators: IVariableDeclaratorOperation (Symbol: T? nt) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'nt = t') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= t') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: T?, IsImplicit) (Syntax: 't') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') Initializer: null "); } [Fact, WorkItem(529280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529280"), WorkItem(546864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546864")] public void ExplicitUDCWithGenericConstraints() { // This compiles successfully in Dev10 dues to a bug; a user-defined conversion // that converts from or to an interface should never be chosen. If you are // converting from Alpha to Beta via standard conversion, then Beta to Gamma // via user-defined conversion, then Gamma to Delta via standard conversion, then // none of Alpha, Beta, Gamma or Delta should be allowed to be interfaces. The // Dev10 compiler only checks Alpha and Delta, not Beta and Gamma. // // Unfortunately, real-world code both in devdiv and in the wild depends on this // behavior, so we are replicating the bug in Roslyn. string source = @"using System; public interface IGoo { void Method(); } public class CT : IGoo { public void Method() { } } public class GenC<T> where T : IGoo { public T valueT; public static explicit operator T(GenC<T> val) { Console.Write(""ExpConv""); return val.valueT; } } public class Test { public static void Main() { var _class = new GenC<IGoo>(); var ret = (CT)_class; } } "; // CompileAndVerify(source, expectedOutput: "ExpConv"); CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC() { string source = @"using System; struct GenS<T> where T : struct { public static int Flag; public static explicit operator T?(GenS<T> s) { Flag = 3; return default(T); } public static implicit operator T(GenS<T> s) { Flag = 2; return default(T); } } class Program { public static void Main() { int? int_a1 = 1; GenS<int>? s28 = new GenS<int>(); // Due to related bug dev10: 742047 is won't fix // so expects the code will call explicit conversion operator int? result28 = s28 ?? int_a1; Console.WriteLine(GenS<int>.Flag); } } "; // Native compiler picks explicit conversion - print 3 CompileAndVerify(source, expectedOutput: "2"); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC_2() { string source = @"using System; struct S { public static explicit operator int?(S? s) { Console.WriteLine(""Explicit""); return 3; } public static implicit operator int(S? s) { Console.WriteLine(""Implicit""); return 2; } } class Program { public static void Main() { int? nn = -1; S? s = new S(); int? ret = s ?? nn; } } "; // Native compiler picks explicit conversion CompileAndVerify(source, expectedOutput: "Implicit"); } [Fact, WorkItem(529363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529363")] public void AssignmentNullCoalescingOperator() { string source = @"using System; class NullCoalescingTest { public static void Main() { int? a; int c; var x = (a = null) ?? (c = 123); Console.WriteLine(c); } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0165: Use of unassigned local variable 'c' // Console.WriteLine(c); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (7,14): warning CS0219: The variable 'a' is assigned but its value is never used // int? a; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a")); } [Fact, WorkItem(529464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529464")] public void MultiDimensionArrayWithDiffTypeIndexDevDiv31328() { var text = @" class A { public static void Main() { byte[,] arr = new byte[1, 1]; ulong i1 = 0; int i2 = 1; arr[i1, i2] = 127; // Dev10 CS0266 } } "; // Dev10 Won't fix bug#31328 for md array with different types' index and involving ulong // CS0266: Cannot implicitly convert type 'ulong' to 'int'. ... CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_SubtractNullLiteral() { var text = @" unsafe class C { long M(int* p) { return p - null; //Dev10 reports CS0019 } } "; // Dev10: the null literal is treated as though it is converted to void*, making the subtraction illegal (ExpressionBinder::GetPtrBinOpSigs). // Roslyn: the null literal is converted to int*, making the subtraction legal. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0181ERR_BadAttributeParamType_Nullable() { var text = @" [Boom] class Boom : System.Attribute { public Boom(int? x = 0) { } static void Main() { typeof(Boom).GetCustomAttributes(true); } } "; // Roslyn: error CS0181: Attribute constructor parameter 'x' has type 'int?', which is not a valid attribute parameter type // Dev10/11: no error, but throw at runtime - System.Reflection.CustomAttributeFormatException CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Boom").WithArguments("x", "int?")); } /// <summary> /// When determining whether the LHS of a null-coalescing operator (??) is non-null, the native compiler strips off casts. /// /// We have decided not to reproduce this behavior. /// </summary> [Fact] public void CastOnLhsOfConditionalOperator() { var text = @" class C { static void Main(string[] args) { int i; int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. int k; int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. int m; int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator } } "; // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // Dev10/11: no error CreateCompilation(text).VerifyDiagnostics( // This is new in Roslyn. // (7,29): error CS0165: Use of unassigned local variable 'i' // int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i"), // These match Dev10. // (10,36): error CS0165: Use of unassigned local variable 'k' // int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k"), // (13,57): error CS0165: Use of unassigned local variable 'm' // int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator Diagnostic(ErrorCode.ERR_UseDefViolation, "m").WithArguments("m")); } [WorkItem(529974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529974")] [Fact] public void TestCollisionForLoopControlVariable() { var source = @" namespace Microsoft.Test.XmlGen.Protocols.Saml2 { using System; using System.Collections.Generic; public class ProxyRestriction { XmlGenIntegerAttribute count; private List<XmlGenAttribute> Attributes { get; set; } public ProxyRestriction() { for (int count = 0; count < 10; count++) { } for (int i = 0; i < this.Attributes.Count; i++) { XmlGenAttribute attribute = this.Attributes[i]; if (attribute.LocalName == null) { if (count is XmlGenIntegerAttribute) { count = (XmlGenIntegerAttribute)attribute; } else { count = new XmlGenIntegerAttribute(attribute); this.Attributes[i] = count; } break; } } if (count == null) { this.Attributes.Add(new XmlGenIntegerAttribute(String.Empty, null, String.Empty, -1, false)); } } } internal class XmlGenAttribute { public object LocalName { get; internal set; } } internal class XmlGenIntegerAttribute : XmlGenAttribute { public XmlGenIntegerAttribute(string empty1, object count, string empty2, int v, bool isPresent) { } public XmlGenIntegerAttribute(XmlGenAttribute attribute) { } } } public class Program { public static void Main() { } }"; // Dev11 reported no errors for the above repro and allowed the name 'count' to bind to different // variables within the same declaration space. According to the old spec the error should be reported. // In Roslyn the single definition rule is relaxed and we do not give an error, but for a different reason. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530301")] public void NoMore_CS0458WRN_AlwaysNull02() { CreateCompilation( @" public class Test { const bool ct = true; public static int Main() { var a = (true & null) ?? null; // CS0458 if (((null & true) == null)) // CS0458 return 0; var b = !(null | false); // CS0458 if ((false | null) != null) // CS0458 return 1; const bool cf = false; var d = ct & null ^ null; // CS0458 - Roslyn Warn this ONLY d ^= !(null | cf); // CS0458 return -1; } } ") // We decided to not report WRN_AlwaysNull in some cases. .VerifyDiagnostics( // Diagnostic(ErrorCode.WRN_AlwaysNull, "true & null").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null & true").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | false").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "false | null").WithArguments("bool?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "ct & null ^ null").WithArguments("bool?") //, // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | cf").WithArguments("bool?") ); } [WorkItem(530403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530403")] [Fact] public void CS0135_local_param_cannot_be_declared() { // Dev11 missed this error. The issue is that an a is a field of c, and then it is a local in parts of d. // by then referring to the field without the this keyword, it should be flagged as declaring a competing variable (as it is confusing). var text = @" using System; public class c { int a = 0; void d(bool b) { if(b) { int a = 1; Console.WriteLine(a); } else { a = 2; } a = 3; Console.WriteLine(a); } } "; var comp = CreateCompilation(text); // In Roslyn the single definition rule is relaxed and we do not give an error. comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] [WorkItem(530518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530518")] public void ExpressionTreeExplicitOpVsConvert() { var text = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static explicit operator int(Test x) { return 1; } static void Main() { Expression<Func<Test, long?>> testExpr1 = x => (long?)x; Console.WriteLine(testExpr1); Expression<Func<Test, decimal?>> testExpr2 = x => (decimal?)x; Console.WriteLine(testExpr2); } } "; // Native Compiler: x => Convert(Convert(op_Explicit(x))) CompileAndVerify(text, expectedOutput: @"x => Convert(Convert(Convert(x))) x => Convert(Convert(Convert(x))) "); } [WorkItem(530531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530531")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] private void ExpressionTreeNoCovertForIdentityConversion() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { static void Main() { Expression<Func<Guid, bool>> e = (x) => x != null; Console.WriteLine(e); Console.WriteLine(e.Compile()(default(Guid))); } } "; // Native compiler: x => (Convert(x) != Convert(null)) CompileAndVerify(source, expectedOutput: @"x => (Convert(x) != null) True "); } [Fact, WorkItem(530548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530548")] public void CS0219WRN_UnreferencedVarAssg_RHSMidRefType() { string source = @" public interface Base { } public struct Derived : Base { } public class Test { public static void Main() { var b1 = new Derived(); // Both Warning CS0219 var b2 = (Base)new Derived(); // Both NO Warn (reference type) var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'b1' is assigned but its value is never used // var b1 = new Derived(); // Both Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1"), // (10,13): warning CS0219: The variable 'b3' is assigned but its value is never used // var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b3").WithArguments("b3")); } [Fact, WorkItem(530556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530556")] public void NoCS0591ERR_InvalidAttributeArgument() { string source = @" using System; [AttributeUsage(AttributeTargets.All + 0xFFFFFF)] class MyAtt : Attribute { } [AttributeUsage((AttributeTargets)0xffff)] class MyAtt1 : Attribute { } public class Test {} "; // Native compiler error CS0591: Invalid value for argument to 'AttributeUsage' attribute CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530586")] public void ThrowOnceInIteratorFinallyBlock() { string source = @" //<Title> Finally block runs twice in iterator</Title> //<RelatedBug>Dev10:473561-->8444?</RelatedBug> using System; using System.Collections; class Program { public static void Main() { var demo = new test(); try { foreach (var x in demo.Goo()) { } } catch (Exception) { Console.Write(""EX ""); } Console.WriteLine(demo.count); } class test { public int count = 0; public IEnumerable Goo() { try { yield return null; try { yield break; } catch { } } finally { Console.Write(""++ ""); ++count; throw new Exception(); } } } } "; // Native print "++ ++ EX 2" var verifier = CompileAndVerify(source, expectedOutput: " ++ EX 1"); // must not load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 101 (0x65) .maxstack 2 .locals init (bool V_0, int V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: brfalse.s IL_0012 IL_000a: ldloc.1 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0033 IL_000e: ldc.i4.0 IL_000f: stloc.0 IL_0010: leave.s IL_0063 IL_0012: ldarg.0 IL_0013: ldc.i4.m1 IL_0014: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0019: ldarg.0 IL_001a: ldc.i4.s -3 IL_001c: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Program.test.<Goo>d__1.<>2__current"" IL_0028: ldarg.0 IL_0029: ldc.i4.1 IL_002a: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_002f: ldc.i4.1 IL_0030: stloc.0 IL_0031: leave.s IL_0063 IL_0033: ldarg.0 IL_0034: ldc.i4.s -3 IL_0036: stfld ""int Program.test.<Goo>d__1.<>1__state"" .try { IL_003b: ldc.i4.0 IL_003c: stloc.0 IL_003d: leave.s IL_004a } catch object { IL_003f: pop IL_0040: leave.s IL_0042 } IL_0042: ldarg.0 IL_0043: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0048: br.s IL_0052 IL_004a: ldarg.0 IL_004b: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0050: leave.s IL_0063 IL_0052: leave.s IL_005b } fault { IL_0054: ldarg.0 IL_0055: call ""void Program.test.<Goo>d__1.Dispose()"" IL_005a: endfinally } IL_005b: ldarg.0 IL_005c: call ""void Program.test.<Goo>d__1.Dispose()"" IL_0061: ldc.i4.1 IL_0062: stloc.0 IL_0063: ldloc.0 IL_0064: ret } "); // must load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.<>m__Finally1()", @" { // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.m1 IL_0002: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0007: ldarg.0 IL_0008: ldfld ""Program.test Program.test.<Goo>d__1.<>4__this"" IL_000d: ldstr ""++ "" IL_0012: call ""void System.Console.Write(string)"" IL_0017: dup IL_0018: ldfld ""int Program.test.count"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stfld ""int Program.test.count"" IL_0024: newobj ""System.Exception..ctor()"" IL_0029: throw } "); } [Fact, WorkItem(530587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530587")] public void NoFormatCharInIDEqual() { string source = @" #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; CompileAndVerify(source, expectedOutput: "1"); // Native print 0 } [Fact, WorkItem(530614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530614")] public void CS1718WRN_ComparisonToSelf_Roslyn() { string source = @" enum esbyte : sbyte { e0, e1 }; public class z_1495j12 { public static void Main() { if (esbyte.e0 == esbyte.e0) { System.Console.WriteLine(""T""); } }} "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (7,5): warning CS1718: Comparison made to same variable; did you mean to compare something else? Diagnostic(ErrorCode.WRN_ComparisonToSelf, "esbyte.e0 == esbyte.e0")); } [Fact, WorkItem(530629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530629")] public void CS0414WRN_UnreferencedFieldAssg_Roslyn() { string source = @" namespace VS7_336319 { public sealed class PredefinedTypes { public class Kind { public static int Decimal; } } public class ExpressionBinder { private static PredefinedTypes PredefinedTypes = null; private void Goo() { if (0 == (int)PredefinedTypes.Kind.Decimal) { } } } } "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (10,40): warning CS0414: The field 'VS7_336319.ExpressionBinder.PredefinedTypes' is assigned but its value is never used // private static PredefinedTypes PredefinedTypes = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "PredefinedTypes").WithArguments("VS7_336319.ExpressionBinder.PredefinedTypes")); } [WorkItem(530666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530666")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] public void ExpressionTreeWithNullableUDCandOperator() { string source = @" using System; using System.Linq.Expressions; struct B { public static implicit operator int?(B x) { return 1; } public static int operator +(B x, int y) { return 2 + y; } static int Main() { Expression<Func<B, int?>> f = x => x + x; var ret = f.Compile()(new B()); Console.WriteLine(ret); return ret.Value - 3; } } "; // Native compiler throw CompileAndVerify(source, expectedOutput: "3"); } [Fact, WorkItem(530696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530696")] public void CS0121Err_AmbiguousMethodCall() { string source = @" class G<T> { } class C { static void M(params double[] x) { System.Console.WriteLine(1); } static void M(params G<int>[] x) { System.Console.WriteLine(2); } static void Main() { M(); } } "; CreateCompilation(source).VerifyDiagnostics( // (15,13): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params double[])' and 'C.M(params G<int>[])' // M(); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params double[])", "C.M(params G<int>[])")); } [Fact, WorkItem(530653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530653")] public void RepeatedObsoleteWarnings() { // <quote source="Srivatsn's comments from bug 16642"> // Inside a method body if you access a static field twice thus: // // var x = ObsoleteType.field1; // var y = ObsoleteType.field1; // // then the native compiler reports ObsoleteType as obsolete only once. This is because the native compiler caches // the lookup of type names for certain cases and doesn't report errors on the second lookup as that just comes // from the cache. Note how I said caches sometimes. If you simply say - // // var x= new ObsoleteType(); // var y = new ObsoleteType(); // // Then the native compiler reports the error twice. I don't think we should replicate this in Roslyn. Note however // that this is a breaking change because if the first line had been #pragma disabled, then the code would compile // without warnings in Dev11 but we will report warnings. I think it's a corner enough scenario and the native // behavior is quirky enough to warrant a break. // </quote> CompileAndVerify(@" using System; [Obsolete] public class ObsoleteType { public static readonly int field = 0; } public class Program { public static void Main() { #pragma warning disable 0612 var x = ObsoleteType.field; #pragma warning restore 0612 var y = ObsoleteType.field; // In Dev11, this line doesn't produce a warning. } }").VerifyDiagnostics( // (15,17): warning CS0612: 'ObsoleteType' is obsolete // var y = ObsoleteType.field; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "ObsoleteType").WithArguments("ObsoleteType")); } [Fact, WorkItem(530303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530303")] public void TestReferenceResolution() { var cs1Compilation = CreateCSharpCompilation("CS1", @"public class CS1 {}", compilationOptions: TestOptions.ReleaseDll); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"public class CS2<T> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation); cs2Verifier.VerifyDiagnostics(); var cs3Compilation = CreateCSharpCompilation("CS3", @"public class CS3 : CS2<CS1> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation, cs2Compilation }); var cs3Verifier = CompileAndVerify(cs3Compilation); cs3Verifier.VerifyDiagnostics(); var cs4Compilation = CreateCSharpCompilation("CS4", @"public class Program { static void Main() { System.Console.WriteLine(typeof(CS3)); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { cs2Compilation, cs3Compilation }); cs4Compilation.VerifyDiagnostics(); } [Fact, WorkItem(531014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531014")] public void TestVariableAndTypeNameClashes() { CompileAndVerify(@" using System; public class Class1 { internal class A4 { internal class B { } internal static string F() { return ""A4""; } } internal class A5 { internal class B { } internal static string F() { return ""A5""; } } internal class A6 { internal class B { } internal static string F() { return ""A6""; } } internal delegate void D(); // Check the weird E.M cases. internal class Outer2 { internal static void F(A4 A4) { A5 A5; const A6 A6 = null; Console.WriteLine(typeof(A4.B)); Console.WriteLine(typeof(A5.B)); Console.WriteLine(typeof(A6.B)); Console.WriteLine(A4.F()); Console.WriteLine(A5.F()); Console.WriteLine(A6.F()); Console.WriteLine(default(A4) == null); Console.WriteLine(default(A5) == null); Console.WriteLine(default(A6) == null); } } }").VerifyDiagnostics( // Breaking Change: See bug 17395. Dev11 had a bug because of which it didn't report the below warnings. // (13,16): warning CS0168: The variable 'A5' is declared but never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "A5").WithArguments("A5"), // (13,29): warning CS0219: The variable 'A6' is assigned but its value is never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "A6").WithArguments("A6")); } [WorkItem(530584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530584")] [Fact] public void NotRuntimeAmbiguousBecauseOfReturnTypes() { var source = @" using System; class Base<T, S> { public virtual int Goo(ref S x) { return 0; } public virtual string Goo(out T x) { x = default(T); return ""Base.Out""; } } class Derived : Base<int, int> { public override string Goo(out int x) { x = 0; return ""Derived.Out""; } static void Main() { int x; Console.WriteLine(new Derived().Goo(out x)); } } "; // BREAK: Dev11 reports WRN_MultipleRuntimeOverrideMatches, but there // is no runtime ambiguity because the return types differ. CompileAndVerify(source, expectedOutput: "Derived.Out"); } [WorkItem(695311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695311")] [Fact] public void NestedCollectionInitializerOnGenericProperty() { var libSource = @" using System.Collections; public interface IAdd { void Add(object o); } public struct S : IEnumerable, IAdd { private ArrayList list; public void Add(object o) { list = list ?? new ArrayList(); list.Add(o); } public IEnumerator GetEnumerator() { return (list ?? new ArrayList()).GetEnumerator(); } } public class C : IEnumerable, IAdd { private readonly ArrayList list = new ArrayList(); public void Add(object o) { list.Add(o); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } } public class Wrapper<T> : IEnumerable where T : IEnumerable, new() { public Wrapper() { this.Item = new T(); } public T Item { get; private set; } public IEnumerator GetEnumerator() { return Item.GetEnumerator(); } } public static class Util { public static int Count(IEnumerable i) { int count = 0; foreach (var v in i) count++; return count; } } "; var libRef = CreateCompilation(libSource, assemblyName: "lib").EmitToImageReference(); { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "03"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : class, IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. // NOTE: The spec will likely be updated to make this illegal. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "3"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); } static Wrapper<T> Goo<T>() where T : struct, IEnumerable, IAdd { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // BREAK: dev11 compiles and prints "0" var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (15,33): error CS1918: Members of property 'Wrapper<T>.Item' of type 'T' cannot be assigned with an object initializer because it is of a value type // return new Wrapper<T> { Item = { 1, 2, 3} }; Diagnostic(ErrorCode.ERR_ValueTypePropertyInObjectInitializer, "Item").WithArguments("Wrapper<T>.Item", "T")); } } [Fact, WorkItem(770424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770424"), WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")] public void UserDefinedShortCircuitingOperators() { var source = @" public class Base { public static bool operator true(Base x) { System.Console.Write(""Base.op_True""); return x != null; } public static bool operator false(Base x) { System.Console.Write(""Base.op_False""); return x == null; } } public class Derived : Base { public static Derived operator&(Derived x, Derived y) { return x; } public static Derived operator|(Derived x, Derived y) { return y; } static void Main() { Derived d = new Derived(); var b = (d && d) || d; } } "; CompileAndVerify(source, expectedOutput: "Base.op_FalseBase.op_True"); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./docs/features/readonly-instance-members.md
# Readonly Instance Members Championed Issue: <https://github.com/dotnet/csharplang/issues/1710> ## Summary [summary]: #summary Provide a way to specify individual instance members on a struct do not modify state, in the same way that `readonly struct` specifies no instance members modify state. It is worth noting that `readonly instance member` != `pure instance member`. A `pure` instance member guarantees no state will be modified. A `readonly` instance member only guarantees that instance state will not be modified. All instance members on a `readonly struct` are implicitly `readonly instance members`. Explicit `readonly instance members` declared on non-readonly structs would behave in the same manner. For example, they would still create hidden copies if you called an instance member (on the current instance or on a field of the instance) which was itself not-readonly. ## Design [design]: #design Allow a user to specify that an instance member is, itself, `readonly` and does not modify the state of the instance (with all the appropriate verification done by the compiler, of course). For example: ```csharp public struct Vector2 { public float x; public float y; public readonly float GetLengthReadonly() { return MathF.Sqrt(LengthSquared); } public float GetLength() { return MathF.Sqrt(LengthSquared); } public readonly float GetLengthIllegal() { var tmp = MathF.Sqrt(LengthSquared); x = tmp; // Compiler error, cannot write x y = tmp; // Compiler error, cannot write y return tmp; } public float LengthSquared { readonly get { return (x * x) + (y * y); } } } public static class MyClass { public static float ExistingBehavior(in Vector2 vector) { // This code causes a hidden copy, the compiler effectively emits: // var tmpVector = vector; // return tmpVector.GetLength(); // // This is done because the compiler doesn't know that `GetLength()` // won't mutate `vector`. return vector.GetLength(); } public static float ReadonlyBehavior(in Vector2 vector) { // This code is emitted exactly as listed. There are no hidden // copies as the `readonly` modifier indicates that the method // won't mutate `vector`. return vector.GetLengthReadonly(); } } ``` Readonly can be applied to property accessors to indicate that `this` will not be mutated in the accessor. ```csharp public int Prop { readonly get { return this._prop1; } } ``` When `readonly` is applied to the property syntax, it means that all accessors are `readonly`. ```csharp public readonly int Prop { get { return this._store["Prop2"]; } set { this._store["Prop2"] = value; } } ``` Similar to the rules for property accessibility modifiers, redundant `readonly` modifiers are not allowed on properties. ```csharp public readonly int Prop1 { readonly get => 42; } // Not allowed public int Prop2 { readonly get => this._store["Prop2"]; readonly set => this._store["Prop2"]; } // Not allowed ``` Readonly can only be applied to accessors which do not mutate the containing type. ```csharp public int Prop { readonly get { return this._prop3; } set { this._prop3 = value; } } ``` ### Auto-properties Readonly can be applied to auto-implemented properties or `get` accessors. However, the compiler will treat all auto-implemented getters as readonly regardless of whether a `readonly` modifier is present. ```csharp // Allowed public readonly int Prop1 { get; } public int Prop2 { readonly get; } public int Prop3 { readonly get; set; } // Not allowed public readonly int Prop4 { get; set; } public int Prop5 { get; readonly set; } ``` ### Events Readonly can be applied to manually-implemented events, but not field-like events. Readonly cannot be applied to individual event accessors (add/remove). ```csharp // Allowed public readonly event Action<EventArgs> Event1 { add { } remove { } } // Not allowed public readonly event Action<EventArgs> Event2; public event Action<EventArgs> Event3 { readonly add { } remove { } } public static readonly event Event4 { add { } remove { } } ``` Some other syntax examples: * Expression bodied members: `public readonly float ExpressionBodiedMember => (x * x) + (y * y);` * Generic constraints: `public readonly void GenericMethod<T>(T value) where T : struct { }` The compiler would emit the instance member, as usual, and would additionally emit a compiler recognized attribute indicating that the instance member does not modify state. This effectively causes the hidden `this` parameter to become `in T` instead of `ref T`. This would allow the user to safely call said instance method without the compiler needing to make a copy. Some more "edge" cases that are explicitly permitted: * Explicit interface implementations are allowed to be `readonly`. * Partial methods are allowed to be `readonly`. Both signatures or neither must have the `readonly` keyword. The restrictions would include: * The `readonly` modifier cannot be applied to static methods, constructors or destructors. * The `readonly` modifier cannot be applied to delegates. * The `readonly` modifier cannot be applied to members of class or interface. ## Compiler API The following public API will be added: - `bool IMethodSymbol.IsDeclaredReadOnly { get; }` indicates that the member is readonly due to having a readonly keyword, or due to being an auto-implemented instance getter on a struct. - `bool IMethodSymbol.IsEffectivelyReadOnly { get; }` indicates that the member is readonly due to IsDeclaredReadOnly, or by the containing type being readonly, except if this method is a constructor. It may be necessary to add additional public API to properties and events. This poses a challenge for properties because `ReadOnly` properties have an existing, different meaning in VB.NET and the `IMethodSymbol.IsReadOnly` API has already shipped to describe that scenario. This specific issue is tracked in https://github.com/dotnet/roslyn/issues/34213.
# Readonly Instance Members Championed Issue: <https://github.com/dotnet/csharplang/issues/1710> ## Summary [summary]: #summary Provide a way to specify individual instance members on a struct do not modify state, in the same way that `readonly struct` specifies no instance members modify state. It is worth noting that `readonly instance member` != `pure instance member`. A `pure` instance member guarantees no state will be modified. A `readonly` instance member only guarantees that instance state will not be modified. All instance members on a `readonly struct` are implicitly `readonly instance members`. Explicit `readonly instance members` declared on non-readonly structs would behave in the same manner. For example, they would still create hidden copies if you called an instance member (on the current instance or on a field of the instance) which was itself not-readonly. ## Design [design]: #design Allow a user to specify that an instance member is, itself, `readonly` and does not modify the state of the instance (with all the appropriate verification done by the compiler, of course). For example: ```csharp public struct Vector2 { public float x; public float y; public readonly float GetLengthReadonly() { return MathF.Sqrt(LengthSquared); } public float GetLength() { return MathF.Sqrt(LengthSquared); } public readonly float GetLengthIllegal() { var tmp = MathF.Sqrt(LengthSquared); x = tmp; // Compiler error, cannot write x y = tmp; // Compiler error, cannot write y return tmp; } public float LengthSquared { readonly get { return (x * x) + (y * y); } } } public static class MyClass { public static float ExistingBehavior(in Vector2 vector) { // This code causes a hidden copy, the compiler effectively emits: // var tmpVector = vector; // return tmpVector.GetLength(); // // This is done because the compiler doesn't know that `GetLength()` // won't mutate `vector`. return vector.GetLength(); } public static float ReadonlyBehavior(in Vector2 vector) { // This code is emitted exactly as listed. There are no hidden // copies as the `readonly` modifier indicates that the method // won't mutate `vector`. return vector.GetLengthReadonly(); } } ``` Readonly can be applied to property accessors to indicate that `this` will not be mutated in the accessor. ```csharp public int Prop { readonly get { return this._prop1; } } ``` When `readonly` is applied to the property syntax, it means that all accessors are `readonly`. ```csharp public readonly int Prop { get { return this._store["Prop2"]; } set { this._store["Prop2"] = value; } } ``` Similar to the rules for property accessibility modifiers, redundant `readonly` modifiers are not allowed on properties. ```csharp public readonly int Prop1 { readonly get => 42; } // Not allowed public int Prop2 { readonly get => this._store["Prop2"]; readonly set => this._store["Prop2"]; } // Not allowed ``` Readonly can only be applied to accessors which do not mutate the containing type. ```csharp public int Prop { readonly get { return this._prop3; } set { this._prop3 = value; } } ``` ### Auto-properties Readonly can be applied to auto-implemented properties or `get` accessors. However, the compiler will treat all auto-implemented getters as readonly regardless of whether a `readonly` modifier is present. ```csharp // Allowed public readonly int Prop1 { get; } public int Prop2 { readonly get; } public int Prop3 { readonly get; set; } // Not allowed public readonly int Prop4 { get; set; } public int Prop5 { get; readonly set; } ``` ### Events Readonly can be applied to manually-implemented events, but not field-like events. Readonly cannot be applied to individual event accessors (add/remove). ```csharp // Allowed public readonly event Action<EventArgs> Event1 { add { } remove { } } // Not allowed public readonly event Action<EventArgs> Event2; public event Action<EventArgs> Event3 { readonly add { } remove { } } public static readonly event Event4 { add { } remove { } } ``` Some other syntax examples: * Expression bodied members: `public readonly float ExpressionBodiedMember => (x * x) + (y * y);` * Generic constraints: `public readonly void GenericMethod<T>(T value) where T : struct { }` The compiler would emit the instance member, as usual, and would additionally emit a compiler recognized attribute indicating that the instance member does not modify state. This effectively causes the hidden `this` parameter to become `in T` instead of `ref T`. This would allow the user to safely call said instance method without the compiler needing to make a copy. Some more "edge" cases that are explicitly permitted: * Explicit interface implementations are allowed to be `readonly`. * Partial methods are allowed to be `readonly`. Both signatures or neither must have the `readonly` keyword. The restrictions would include: * The `readonly` modifier cannot be applied to static methods, constructors or destructors. * The `readonly` modifier cannot be applied to delegates. * The `readonly` modifier cannot be applied to members of class or interface. ## Compiler API The following public API will be added: - `bool IMethodSymbol.IsDeclaredReadOnly { get; }` indicates that the member is readonly due to having a readonly keyword, or due to being an auto-implemented instance getter on a struct. - `bool IMethodSymbol.IsEffectivelyReadOnly { get; }` indicates that the member is readonly due to IsDeclaredReadOnly, or by the containing type being readonly, except if this method is a constructor. It may be necessary to add additional public API to properties and events. This poses a challenge for properties because `ReadOnly` properties have an existing, different meaning in VB.NET and the `IMethodSymbol.IsReadOnly` API has already shipped to describe that scenario. This specific issue is tracked in https://github.com/dotnet/roslyn/issues/34213.
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDefaultValueOperation.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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDefaultValueOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_01() { string source = @" class C { void M(int i) /*<bind>*/{ i = default(int); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = default(int);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = default(int)') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0) (Syntax: 'default(int)') "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_02() { string source = @" class C { void M(string s) /*<bind>*/{ s = default; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = default;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 's = default') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null) (Syntax: 'default')"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_03() { string source = @" class C { void M(string s) /*<bind>*/{ M2(default); }/*</bind>*/ static void M2(int x) { } static void M2(string x) { } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M2(int)' and 'C.M2(string)' // M2(default); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("C.M2(int)", "C.M2(string)").WithLocation(6, 9) }; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2(default);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(default)') Children(1): IDefaultValueOperation (OperationKind.DefaultValue, Type: ?) (Syntax: 'default')"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDefaultValueOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_01() { string source = @" class C { void M(int i) /*<bind>*/{ i = default(int); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = default(int);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = default(int)') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0) (Syntax: 'default(int)') "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_02() { string source = @" class C { void M(string s) /*<bind>*/{ s = default; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = default;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 's = default') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null) (Syntax: 'default')"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueFlow_03() { string source = @" class C { void M(string s) /*<bind>*/{ M2(default); }/*</bind>*/ static void M2(int x) { } static void M2(string x) { } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M2(int)' and 'C.M2(string)' // M2(default); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("C.M2(int)", "C.M2(string)").WithLocation(6, 9) }; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2(default);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(default)') Children(1): IDefaultValueOperation (OperationKind.DefaultValue, Type: ?) (Syntax: 'default')"; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Test/PdbUtilities/Shared/DummyMetadataImport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader.PortablePdb; using System.Reflection; namespace Roslyn.Test.PdbUtilities { internal sealed class DummyMetadataImport : IMetadataImport, IDisposable { private readonly MetadataReader _metadataReaderOpt; private readonly IDisposable _metadataOwnerOpt; private readonly List<GCHandle> _pinnedBuffers; public DummyMetadataImport(MetadataReader metadataReaderOpt, IDisposable metadataOwnerOpt) { _metadataReaderOpt = metadataReaderOpt; _pinnedBuffers = new List<GCHandle>(); _metadataOwnerOpt = metadataOwnerOpt; } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool disposing) { _metadataOwnerOpt?.Dispose(); foreach (var pinnedBuffer in _pinnedBuffers) { pinnedBuffer.Free(); } } ~DummyMetadataImport() { Dispose(false); } [PreserveSig] public unsafe int GetSigFromToken( int tkSignature, // Signature token. out byte* ppvSig, // return pointer to signature blob out int pcbSig) // return size of signature { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var sig = _metadataReaderOpt.GetStandaloneSignature((StandaloneSignatureHandle)MetadataTokens.Handle(tkSignature)); var signature = _metadataReaderOpt.GetBlobBytes(sig.Signature); GCHandle pinnedBuffer = GCHandle.Alloc(signature, GCHandleType.Pinned); ppvSig = (byte*)pinnedBuffer.AddrOfPinnedObject(); pcbSig = signature.Length; #pragma warning disable RS0042 // Do not copy value _pinnedBuffers.Add(pinnedBuffer); #pragma warning restore RS0042 // Do not copy value return 0; } public void GetTypeDefProps( int typeDefinition, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength, [MarshalAs(UnmanagedType.U4)] out TypeAttributes attributes, out int baseType) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeDefinitionHandle)MetadataTokens.Handle(typeDefinition); var typeDef = _metadataReaderOpt.GetTypeDefinition(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeDef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeDef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeDef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeDef.Name).Length; } baseType = MetadataTokens.GetToken(typeDef.BaseType); attributes = typeDef.Attributes; } public void GetTypeRefProps( int typeReference, out int resolutionScope, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeReferenceHandle)MetadataTokens.Handle(typeReference); var typeRef = _metadataReaderOpt.GetTypeReference(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeRef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeRef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeRef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeRef.Name).Length; } resolutionScope = MetadataTokens.GetToken(typeRef.ResolutionScope); } #region Not Implemented public void CloseEnum(uint handleEnum) { throw new NotImplementedException(); } public uint CountEnum(uint handleEnum) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint handlePointerEnum, uint tk, uint tokenType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayCustomAttributes, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumEvents(ref uint handlePointerEnum, uint td, uint* arrayEvents, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumFields(ref uint handlePointerEnum, uint cl, uint* arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayImpls, uint countMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint handlePointerEnum, uint tokenParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMemberRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumMembers(ref uint handlePointerEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodDecl, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumMethods(ref uint handlePointerEnum, uint cl, uint* arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayEventProp, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint EnumParams(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayParams, uint countMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint handlePointerEnum, uint tk, uint dwordActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayPermission, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumProperties(ref uint handlePointerEnum, uint td, uint* arrayProperties, uint countMax) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arraySignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeDefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayStrings, uint cmax) { throw new NotImplementedException(); } public uint FindField(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMember(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindTypeDefByName(string stringTypeDef, uint tokenEnclosingClass) { throw new NotImplementedException(); } public uint FindTypeRef(uint tokenResolutionScope, string stringName) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ulong[] arrayFieldOffset, uint countMax, out uint countPointerFieldOffset) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeByName(uint tokenObj, string stringName, out void* ppData) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out void* ppBlob) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pointerClass, StringBuilder stringEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public unsafe uint GetFieldMarshal(uint tk, out byte* ppvNativeType) { throw new NotImplementedException(); } public unsafe uint GetFieldProps(uint mb, out uint pointerClass, StringBuilder stringField, uint cchField, out uint pchField, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public uint GetInterfaceImplProps(uint impl, out uint pointerClass) { throw new NotImplementedException(); } public unsafe uint GetMemberProps(uint mb, out uint pointerClass, StringBuilder stringMember, uint cchMember, out uint pchMember, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder stringMember, uint cchMember, out uint pchMember, out byte* ppvSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pointerClass, IntPtr stringMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tokenEventProp) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder stringName, uint cchName) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public unsafe uint GetNativeCallConvFromSig(void* voidPointerSig, uint byteCountSig) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint typeDefNestedClass) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulongParamSeq, out uint pointerParam) { throw new NotImplementedException(); } public unsafe uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder stringName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetPermissionSetProps(uint pm, out uint pdwAction, out void* ppvPermission) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder stringImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public unsafe uint GetPropertyProps(uint prop, out uint pointerClass, StringBuilder stringProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out byte* ppvSig, out uint bytePointerSig, out uint pdwCPlusTypeFlag, out void* ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder stringName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public unsafe uint GetTypeSpecFromToken(uint typespec, out byte* ppvSig) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder stringString, uint cchString) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } [return: MarshalAs(UnmanagedType.Bool)] public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public void ResetEnum(uint handleEnum, uint ulongPos) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope) { throw new NotImplementedException(); } #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.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader.PortablePdb; using System.Reflection; namespace Roslyn.Test.PdbUtilities { internal sealed class DummyMetadataImport : IMetadataImport, IDisposable { private readonly MetadataReader _metadataReaderOpt; private readonly IDisposable _metadataOwnerOpt; private readonly List<GCHandle> _pinnedBuffers; public DummyMetadataImport(MetadataReader metadataReaderOpt, IDisposable metadataOwnerOpt) { _metadataReaderOpt = metadataReaderOpt; _pinnedBuffers = new List<GCHandle>(); _metadataOwnerOpt = metadataOwnerOpt; } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool disposing) { _metadataOwnerOpt?.Dispose(); foreach (var pinnedBuffer in _pinnedBuffers) { pinnedBuffer.Free(); } } ~DummyMetadataImport() { Dispose(false); } [PreserveSig] public unsafe int GetSigFromToken( int tkSignature, // Signature token. out byte* ppvSig, // return pointer to signature blob out int pcbSig) // return size of signature { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var sig = _metadataReaderOpt.GetStandaloneSignature((StandaloneSignatureHandle)MetadataTokens.Handle(tkSignature)); var signature = _metadataReaderOpt.GetBlobBytes(sig.Signature); GCHandle pinnedBuffer = GCHandle.Alloc(signature, GCHandleType.Pinned); ppvSig = (byte*)pinnedBuffer.AddrOfPinnedObject(); pcbSig = signature.Length; #pragma warning disable RS0042 // Do not copy value _pinnedBuffers.Add(pinnedBuffer); #pragma warning restore RS0042 // Do not copy value return 0; } public void GetTypeDefProps( int typeDefinition, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength, [MarshalAs(UnmanagedType.U4)] out TypeAttributes attributes, out int baseType) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeDefinitionHandle)MetadataTokens.Handle(typeDefinition); var typeDef = _metadataReaderOpt.GetTypeDefinition(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeDef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeDef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeDef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeDef.Name).Length; } baseType = MetadataTokens.GetToken(typeDef.BaseType); attributes = typeDef.Attributes; } public void GetTypeRefProps( int typeReference, out int resolutionScope, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeReferenceHandle)MetadataTokens.Handle(typeReference); var typeRef = _metadataReaderOpt.GetTypeReference(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeRef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeRef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeRef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeRef.Name).Length; } resolutionScope = MetadataTokens.GetToken(typeRef.ResolutionScope); } #region Not Implemented public void CloseEnum(uint handleEnum) { throw new NotImplementedException(); } public uint CountEnum(uint handleEnum) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint handlePointerEnum, uint tk, uint tokenType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayCustomAttributes, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumEvents(ref uint handlePointerEnum, uint td, uint* arrayEvents, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumFields(ref uint handlePointerEnum, uint cl, uint* arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayImpls, uint countMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint handlePointerEnum, uint tokenParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMemberRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumMembers(ref uint handlePointerEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodDecl, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumMethods(ref uint handlePointerEnum, uint cl, uint* arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayEventProp, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint EnumParams(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayParams, uint countMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint handlePointerEnum, uint tk, uint dwordActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayPermission, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumProperties(ref uint handlePointerEnum, uint td, uint* arrayProperties, uint countMax) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arraySignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeDefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayStrings, uint cmax) { throw new NotImplementedException(); } public uint FindField(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMember(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindTypeDefByName(string stringTypeDef, uint tokenEnclosingClass) { throw new NotImplementedException(); } public uint FindTypeRef(uint tokenResolutionScope, string stringName) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ulong[] arrayFieldOffset, uint countMax, out uint countPointerFieldOffset) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeByName(uint tokenObj, string stringName, out void* ppData) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out void* ppBlob) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pointerClass, StringBuilder stringEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public unsafe uint GetFieldMarshal(uint tk, out byte* ppvNativeType) { throw new NotImplementedException(); } public unsafe uint GetFieldProps(uint mb, out uint pointerClass, StringBuilder stringField, uint cchField, out uint pchField, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public uint GetInterfaceImplProps(uint impl, out uint pointerClass) { throw new NotImplementedException(); } public unsafe uint GetMemberProps(uint mb, out uint pointerClass, StringBuilder stringMember, uint cchMember, out uint pchMember, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder stringMember, uint cchMember, out uint pchMember, out byte* ppvSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pointerClass, IntPtr stringMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tokenEventProp) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder stringName, uint cchName) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public unsafe uint GetNativeCallConvFromSig(void* voidPointerSig, uint byteCountSig) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint typeDefNestedClass) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulongParamSeq, out uint pointerParam) { throw new NotImplementedException(); } public unsafe uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder stringName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetPermissionSetProps(uint pm, out uint pdwAction, out void* ppvPermission) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder stringImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public unsafe uint GetPropertyProps(uint prop, out uint pointerClass, StringBuilder stringProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out byte* ppvSig, out uint bytePointerSig, out uint pdwCPlusTypeFlag, out void* ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder stringName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public unsafe uint GetTypeSpecFromToken(uint typespec, out byte* ppvSig) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder stringString, uint cchString) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } [return: MarshalAs(UnmanagedType.Bool)] public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public void ResetEnum(uint handleEnum, uint ulongPos) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope) { throw new NotImplementedException(); } #endregion } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/CommentSelection/ICommentSelectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CommentSelection { internal interface ICommentSelectionService : ILanguageService { Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, 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. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CommentSelection { internal interface ICommentSelectionService : ILanguageService { Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./docs/contributing/Documentation for IDE CodeStyle analyzers.md
# Documentation for IDE CodeStyle analyzers ## Overview 1. Official documentation for all [IDE analyzer diagnostic IDs](../../src/Analyzers/Core/Analyzers/IDEDiagnosticIds.cs) is added to `dotnet/docs` repo at <https://github.com/dotnet/docs/tree/main/docs/fundamentals/code-analysis/style-rules>. 2. Each IDE diagnostic ID has a dedicated documentation page. For example: 1. Diagnostic with code style option: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0011> 2. Diagnostic without code style option: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0004> 3. Multiple diagnostic IDs sharing the same option(s): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0003-ide0009> 3. We have tabular indices for IDE diagnostic IDs and code style options for easier reference and navigation: 1. Primary index (rule ID + code style options): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/> 2. Secondary index (code style options only): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules> 3. Indices for each preference/option group. For example: 1. Modifier preferences: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/modifier-preferences> 2. Expression-level preferences: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/expression-level-preferences> ## Action items when adding or updating IDE analyzers Roslyn IDE team (@dotnet/roslyn-ide) is responsible for ensuring that the documentation for IDE analyzers is up-to-date. Whenever we add a new IDE analyzer, add new code style option(s) OR update semantics of existing IDE analyzers the following needs to be done: 1. **Action required in [dotnet\docs](https://github.com/dotnet/docs) repo**: 1. If you _creating a Roslyn PR for an IDE analyzer_: 1. Please follow the steps at [Contribute docs for 'IDExxxx' rules](https://docs.microsoft.com/contribute/dotnet/dotnet-contribute-code-analysis#contribute-docs-for-idexxxx-rules) to add documentation for IDE analyzers to [dotnet\docs](https://github.com/dotnet/docs) repo. 2. Ideally, the documentation PR should be created in parallel to the Roslyn PR or immediately following the approval/merge of Roslyn PR. 2. If you are _reviewing a Roslyn PR for an IDE analyzer_: 1. Please ensure that the analyzer author is made aware of the above doc contribution requirements, especially if it is a community PR. 2. If the documentation PR in is not being created in parallel to the Roslyn PR, please ensure that a [new doc issue](https://github.com/dotnet/docs/issues) is filed in `dotnet/docs` repo to track this work. 2. **No action required in Roslyn repo**: Help links have been hooked up to IDE code style analyzers in Roslyn repo in the base analyzer types, so every new IDE analyzer diagnostic ID will automatically have `https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ideXXXX` as its help link. There is no action required on the Roslyn PR to ensure this linking. If you feel any of the existing IDE rule docs have insufficient or incorrect information, please submit a PR to [dotnet\docs](https://github.com/dotnet/docs) repo to update the documentation.
# Documentation for IDE CodeStyle analyzers ## Overview 1. Official documentation for all [IDE analyzer diagnostic IDs](../../src/Analyzers/Core/Analyzers/IDEDiagnosticIds.cs) is added to `dotnet/docs` repo at <https://github.com/dotnet/docs/tree/main/docs/fundamentals/code-analysis/style-rules>. 2. Each IDE diagnostic ID has a dedicated documentation page. For example: 1. Diagnostic with code style option: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0011> 2. Diagnostic without code style option: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0004> 3. Multiple diagnostic IDs sharing the same option(s): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0003-ide0009> 3. We have tabular indices for IDE diagnostic IDs and code style options for easier reference and navigation: 1. Primary index (rule ID + code style options): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/> 2. Secondary index (code style options only): <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules> 3. Indices for each preference/option group. For example: 1. Modifier preferences: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/modifier-preferences> 2. Expression-level preferences: <https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/expression-level-preferences> ## Action items when adding or updating IDE analyzers Roslyn IDE team (@dotnet/roslyn-ide) is responsible for ensuring that the documentation for IDE analyzers is up-to-date. Whenever we add a new IDE analyzer, add new code style option(s) OR update semantics of existing IDE analyzers the following needs to be done: 1. **Action required in [dotnet\docs](https://github.com/dotnet/docs) repo**: 1. If you _creating a Roslyn PR for an IDE analyzer_: 1. Please follow the steps at [Contribute docs for 'IDExxxx' rules](https://docs.microsoft.com/contribute/dotnet/dotnet-contribute-code-analysis#contribute-docs-for-idexxxx-rules) to add documentation for IDE analyzers to [dotnet\docs](https://github.com/dotnet/docs) repo. 2. Ideally, the documentation PR should be created in parallel to the Roslyn PR or immediately following the approval/merge of Roslyn PR. 2. If you are _reviewing a Roslyn PR for an IDE analyzer_: 1. Please ensure that the analyzer author is made aware of the above doc contribution requirements, especially if it is a community PR. 2. If the documentation PR in is not being created in parallel to the Roslyn PR, please ensure that a [new doc issue](https://github.com/dotnet/docs/issues) is filed in `dotnet/docs` repo to track this work. 2. **No action required in Roslyn repo**: Help links have been hooked up to IDE code style analyzers in Roslyn repo in the base analyzer types, so every new IDE analyzer diagnostic ID will automatically have `https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ideXXXX` as its help link. There is no action required on the Roslyn PR to ensure this linking. If you feel any of the existing IDE rule docs have insufficient or incorrect information, please submit a PR to [dotnet\docs](https://github.com/dotnet/docs) repo to update the documentation.
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarItemSelectedEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Editor { internal sealed class NavigationBarItemSelectedEventArgs : EventArgs { public NavigationBarItem Item { get; } public NavigationBarItemSelectedEventArgs(NavigationBarItem item) { Item = item; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Editor { internal sealed class NavigationBarItemSelectedEventArgs : EventArgs { public NavigationBarItem Item { get; } public NavigationBarItemSelectedEventArgs(NavigationBarItem item) { Item = item; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlElementHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlElementHighlighter Inherits AbstractKeywordHighlighter(Of XmlNodeSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As XmlNodeSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim xmlElement = node.GetAncestor(Of XmlElementSyntax)() With xmlElement If xmlElement IsNot Nothing AndAlso Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then With .StartTag If .Attributes.Count = 0 Then highlights.Add(.Span) Else highlights.Add(TextSpan.FromBounds(.LessThanToken.SpanStart, .Name.Span.End)) highlights.Add(.GreaterThanToken.Span) End If End With highlights.Add(.EndTag.Span) End If End With End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlElementHighlighter Inherits AbstractKeywordHighlighter(Of XmlNodeSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As XmlNodeSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim xmlElement = node.GetAncestor(Of XmlElementSyntax)() With xmlElement If xmlElement IsNot Nothing AndAlso Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then With .StartTag If .Attributes.Count = 0 Then highlights.Add(.Span) Else highlights.Add(TextSpan.FromBounds(.LessThanToken.SpanStart, .Name.Span.End)) highlights.Add(.GreaterThanToken.Span) End If End With highlights.Add(.EndTag.Span) End If End With End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Symbols/EmbeddedSymbols/VbCoreSourceText.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. Option Strict On Option Infer On Option Explicit On Option Compare Binary Namespace Global.Microsoft.VisualBasic Namespace CompilerServices <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class EmbeddedOperators Private Sub New() End Sub Public Shared Function CompareString(Left As String, Right As String, TextCompare As Boolean) As Integer If Left Is Right Then Return 0 End If If Left Is Nothing Then If Right.Length() = 0 Then Return 0 End If Return -1 End If If Right Is Nothing Then If Left.Length() = 0 Then Return 0 End If Return 1 End If Dim Result As Integer If TextCompare Then Dim OptionCompareTextFlags As Global.System.Globalization.CompareOptions = (Global.System.Globalization.CompareOptions.IgnoreCase Or Global.System.Globalization.CompareOptions.IgnoreWidth Or Global.System.Globalization.CompareOptions.IgnoreKanaType) Result = Conversions.GetCultureInfo().CompareInfo.Compare(Left, Right, OptionCompareTextFlags) Else Result = Global.System.String.CompareOrdinal(Left, Right) End If If Result = 0 Then Return 0 ElseIf Result > 0 Then Return 1 Else Return -1 End If End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class Conversions Private Sub New() End Sub Private Shared Function GetEnumValue(Value As Object) As Object Dim underlyingType = System.Enum.GetUnderlyingType(Value.GetType()) If underlyingType.Equals(GetType(SByte)) Then Return DirectCast(Value, SByte) ElseIf underlyingType.Equals(GetType(Byte)) Then Return DirectCast(Value, Byte) ElseIf underlyingType.Equals(GetType(Global.System.Int16)) Then Return DirectCast(Value, Global.System.Int16) ElseIf underlyingType.Equals(GetType(Global.System.UInt16)) Then Return DirectCast(Value, Global.System.UInt16) ElseIf underlyingType.Equals(GetType(Global.System.Int32)) Then Return DirectCast(Value, Global.System.Int32) ElseIf underlyingType.Equals(GetType(Global.System.UInt32)) Then Return DirectCast(Value, Global.System.UInt32) ElseIf underlyingType.Equals(GetType(Global.System.Int64)) Then Return DirectCast(Value, Global.System.Int64) ElseIf underlyingType.Equals(GetType(Global.System.UInt64)) Then Return DirectCast(Value, Global.System.UInt64) Else Throw New Global.System.InvalidCastException End If End Function Public Shared Function ToBoolean(Value As String) As Boolean If Value Is Nothing Then Value = "" End If Try Dim loc As Global.System.Globalization.CultureInfo = GetCultureInfo() If loc.CompareInfo.Compare(Value, Boolean.FalseString, Global.System.Globalization.CompareOptions.IgnoreCase) = 0 Then Return False ElseIf loc.CompareInfo.Compare(Value, Boolean.TrueString, Global.System.Globalization.CompareOptions.IgnoreCase) = 0 Then Return True End If Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CBool(i64Value) End If Return CBool(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToBoolean(Value As Object) As Boolean If Value Is Nothing Then Return False End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CBool(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CBool(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CBool(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CBool(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CBool(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CBool(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CBool(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CBool(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CBool(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CBool(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CBool(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CBool(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CBool(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToByte(Value As String) As Byte If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CByte(i64Value) End If Return CByte(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToByte(Value As Object) As Byte If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CByte(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CByte(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CByte(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CByte(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CByte(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CByte(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CByte(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CByte(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CByte(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CByte(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CByte(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CByte(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CByte(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToSByte(Value As String) As SByte If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CSByte(i64Value) End If Return CSByte(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToSByte(Value As Object) As SByte If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CSByte(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CSByte(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CSByte(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CSByte(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CSByte(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CSByte(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CSByte(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CSByte(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CSByte(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CSByte(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CSByte(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CSByte(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CSByte(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToShort(Value As String) As Short If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CShort(i64Value) End If Return CShort(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToShort(Value As Object) As Short If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CShort(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CShort(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CShort(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CShort(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CShort(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CShort(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CShort(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CShort(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CShort(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CShort(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CShort(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CShort(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CShort(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUShort(Value As String) As UShort If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CUShort(i64Value) End If Return CUShort(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUShort(Value As Object) As UShort If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CUShort(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CUShort(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CUShort(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CUShort(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CUShort(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CUShort(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CUShort(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CUShort(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CUShort(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CUShort(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CUShort(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CUShort(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CUShort(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToInteger(Value As String) As Integer If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CInt(i64Value) End If Return CInt(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToInteger(Value As Object) As Integer If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CInt(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CInt(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CInt(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CInt(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CInt(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CInt(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CInt(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CInt(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CInt(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CInt(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CInt(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CInt(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CInt(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUInteger(Value As String) As UInteger If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CUInt(i64Value) End If Return CUInt(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUInteger(Value As Object) As UInteger If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CUInt(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CUInt(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CUInt(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CUInt(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CUInt(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CUInt(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CUInt(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CUInt(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CUInt(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CUInt(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CUInt(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CUInt(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CUInt(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToLong(Value As String) As Long If (Value Is Nothing) Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CLng(i64Value) End If Return CLng(ParseDecimal(Value, Nothing)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToLong(Value As Object) As Long If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CLng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CLng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CLng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CLng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CLng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CLng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CLng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CLng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CLng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CLng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CLng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CLng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CLng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToULong(Value As String) As ULong If (Value Is Nothing) Then Return 0 End If Try Dim ui64Value As Global.System.UInt64 If IsHexOrOctValue(Value, ui64Value) Then Return CULng(ui64Value) End If Return CULng(ParseDecimal(Value, Nothing)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToULong(Value As Object) As ULong If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CULng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CULng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CULng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CULng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CULng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CULng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CULng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CULng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CULng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CULng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CULng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CULng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CULng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToDecimal(Value As Boolean) As Decimal If Value Then Return -1D Else Return 0D End If End Function Public Shared Function ToDecimal(Value As String) As Decimal If Value Is Nothing Then Return 0D End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CDec(i64Value) End If Return ParseDecimal(Value, Nothing) Catch e1 As Global.System.OverflowException Throw e1 Catch e2 As Global.System.FormatException Throw New Global.System.InvalidCastException(e2.Message, e2) End Try End Function Public Shared Function ToDecimal(Value As Object) As Decimal If Value Is Nothing Then Return 0D End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CDec(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CDec(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CDec(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CDec(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CDec(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CDec(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CDec(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CDec(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CDec(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CDec(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CDec(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CDec(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CDec(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Private Shared Function ParseDecimal(Value As String, NumberFormat As Global.System.Globalization.NumberFormatInfo) As Decimal Dim NormalizedNumberFormat As Global.System.Globalization.NumberFormatInfo Dim culture As Global.System.Globalization.CultureInfo = GetCultureInfo() If NumberFormat Is Nothing Then NumberFormat = culture.NumberFormat End If NormalizedNumberFormat = GetNormalizedNumberFormat(NumberFormat) Const flags As Global.System.Globalization.NumberStyles = Global.System.Globalization.NumberStyles.AllowDecimalPoint Or Global.System.Globalization.NumberStyles.AllowExponent Or Global.System.Globalization.NumberStyles.AllowLeadingSign Or Global.System.Globalization.NumberStyles.AllowLeadingWhite Or Global.System.Globalization.NumberStyles.AllowThousands Or Global.System.Globalization.NumberStyles.AllowTrailingSign Or Global.System.Globalization.NumberStyles.AllowParentheses Or Global.System.Globalization.NumberStyles.AllowTrailingWhite Or Global.System.Globalization.NumberStyles.AllowCurrencySymbol Value = ToHalfwidthNumbers(Value, culture) Try Return Global.System.Decimal.Parse(Value, flags, NormalizedNumberFormat) Catch FormatEx As Global.System.FormatException When Not (NumberFormat Is NormalizedNumberFormat) Return Global.System.Decimal.Parse(Value, flags, NumberFormat) Catch Ex As Global.System.Exception Throw Ex End Try End Function Private Shared Function GetNormalizedNumberFormat(InNumberFormat As Global.System.Globalization.NumberFormatInfo) As Global.System.Globalization.NumberFormatInfo Dim OutNumberFormat As Global.System.Globalization.NumberFormatInfo With InNumberFormat If (Not .CurrencyDecimalSeparator Is Nothing) AndAlso (Not .NumberDecimalSeparator Is Nothing) AndAlso (Not .CurrencyGroupSeparator Is Nothing) AndAlso (Not .NumberGroupSeparator Is Nothing) AndAlso (.CurrencyDecimalSeparator.Length = 1) AndAlso (.NumberDecimalSeparator.Length = 1) AndAlso (.CurrencyGroupSeparator.Length = 1) AndAlso (.NumberGroupSeparator.Length = 1) AndAlso (.CurrencyDecimalSeparator.Chars(0) = .NumberDecimalSeparator.Chars(0)) AndAlso (.CurrencyGroupSeparator.Chars(0) = .NumberGroupSeparator.Chars(0)) AndAlso (.CurrencyDecimalDigits = .NumberDecimalDigits) Then Return InNumberFormat End If End With With InNumberFormat If (Not .CurrencyDecimalSeparator Is Nothing) AndAlso (Not .NumberDecimalSeparator Is Nothing) AndAlso (.CurrencyDecimalSeparator.Length = .NumberDecimalSeparator.Length) AndAlso (Not .CurrencyGroupSeparator Is Nothing) AndAlso (Not .NumberGroupSeparator Is Nothing) AndAlso (.CurrencyGroupSeparator.Length = .NumberGroupSeparator.Length) Then Dim i As Integer For i = 0 To .CurrencyDecimalSeparator.Length - 1 If (.CurrencyDecimalSeparator.Chars(i) <> .NumberDecimalSeparator.Chars(i)) Then GoTo MisMatch Next For i = 0 To .CurrencyGroupSeparator.Length - 1 If (.CurrencyGroupSeparator.Chars(i) <> .NumberGroupSeparator.Chars(i)) Then GoTo MisMatch Next Return InNumberFormat End If End With MisMatch: OutNumberFormat = DirectCast(InNumberFormat.Clone, Global.System.Globalization.NumberFormatInfo) With OutNumberFormat .CurrencyDecimalSeparator = .NumberDecimalSeparator .CurrencyGroupSeparator = .NumberGroupSeparator .CurrencyDecimalDigits = .NumberDecimalDigits End With Return OutNumberFormat End Function Public Shared Function ToSingle(Value As String) As Single If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CSng(i64Value) End If Dim Result As Double = ParseDouble(Value) If (Result < Global.System.Single.MinValue OrElse Result > Global.System.Single.MaxValue) AndAlso Not Global.System.Double.IsInfinity(Result) Then Throw New Global.System.OverflowException End If Return CSng(Result) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToSingle(Value As Object) As Single If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CSng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CSng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CSng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CSng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CSng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CSng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CSng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CSng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CSng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CSng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CSng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CSng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CSng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToDouble(Value As String) As Double If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CDbl(i64Value) End If Return ParseDouble(Value) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToDouble(Value As Object) As Double If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CDbl(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CDbl(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CDbl(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CDbl(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CDbl(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CDbl(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CDbl(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CDbl(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CDbl(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CDbl(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CDbl(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CDbl(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CDbl(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Private Shared Function ParseDouble(Value As String) As Double Dim NormalizedNumberFormat As Global.System.Globalization.NumberFormatInfo Dim culture As Global.System.Globalization.CultureInfo = GetCultureInfo() Dim NumberFormat As Global.System.Globalization.NumberFormatInfo = culture.NumberFormat NormalizedNumberFormat = GetNormalizedNumberFormat(NumberFormat) Const flags As Global.System.Globalization.NumberStyles = Global.System.Globalization.NumberStyles.AllowDecimalPoint Or Global.System.Globalization.NumberStyles.AllowExponent Or Global.System.Globalization.NumberStyles.AllowLeadingSign Or Global.System.Globalization.NumberStyles.AllowLeadingWhite Or Global.System.Globalization.NumberStyles.AllowThousands Or Global.System.Globalization.NumberStyles.AllowTrailingSign Or Global.System.Globalization.NumberStyles.AllowParentheses Or Global.System.Globalization.NumberStyles.AllowTrailingWhite Or Global.System.Globalization.NumberStyles.AllowCurrencySymbol Value = ToHalfwidthNumbers(Value, culture) Try Return Global.System.Double.Parse(Value, flags, NormalizedNumberFormat) Catch FormatEx As Global.System.FormatException When Not (NumberFormat Is NormalizedNumberFormat) Return Global.System.Double.Parse(Value, flags, NumberFormat) Catch Ex As Global.System.Exception Throw Ex End Try End Function Public Shared Function ToDate(Value As String) As Date Dim ParsedDate As Global.System.DateTime Const ParseStyle As Global.System.Globalization.DateTimeStyles = Global.System.Globalization.DateTimeStyles.AllowWhiteSpaces Or Global.System.Globalization.DateTimeStyles.NoCurrentDateDefault Dim Culture As Global.System.Globalization.CultureInfo = GetCultureInfo() Dim result = Global.System.DateTime.TryParse(ToHalfwidthNumbers(Value, Culture), Culture, ParseStyle, ParsedDate) If result Then Return ParsedDate Else Throw New Global.System.InvalidCastException() End If End Function Public Shared Function ToDate(Value As Object) As Date If Value Is Nothing Then Return Nothing End If If TypeOf Value Is Global.System.DateTime Then Return CDate(DirectCast(Value, Global.System.DateTime)) ElseIf TypeOf Value Is String Then Return CDate(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToChar(Value As String) As Char If (Value Is Nothing) OrElse (Value.Length = 0) Then Return Global.System.Convert.ToChar(0 And &HFFFFI) End If Return Value.Chars(0) End Function Public Shared Function ToChar(Value As Object) As Char If Value Is Nothing Then Return Global.System.Convert.ToChar(0 And &HFFFFI) End If If TypeOf Value Is Char Then Return CChar(DirectCast(Value, Char)) ElseIf TypeOf Value Is String Then Return CChar(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToCharArrayRankOne(Value As String) As Char() If Value Is Nothing Then Value = "" End If Return Value.ToCharArray() End Function Public Shared Function ToCharArrayRankOne(Value As Object) As Char() If Value Is Nothing Then Return "".ToCharArray() End If Dim ArrayValue As Char() = TryCast(Value, Char()) If ArrayValue IsNot Nothing AndAlso ArrayValue.Rank = 1 Then Return ArrayValue ElseIf TypeOf Value Is String Then Return DirectCast(Value, String).ToCharArray() End If Throw New Global.System.InvalidCastException() End Function Public Shared Shadows Function ToString(Value As Short) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Integer) As String Return Value.ToString() End Function <Global.System.CLSCompliant(False)> Public Shared Shadows Function ToString(Value As UInteger) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Long) As String Return Value.ToString() End Function <Global.System.CLSCompliant(False)> Public Shared Shadows Function ToString(Value As ULong) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Single) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Double) As String Return Value.ToString("G") End Function Public Shared Shadows Function ToString(Value As Date) As String Dim TimeTicks As Long = Value.TimeOfDay.Ticks If (TimeTicks = Value.Ticks) OrElse (Value.Year = 1899 AndAlso Value.Month = 12 AndAlso Value.Day = 30) Then Return Value.ToString("T") ElseIf TimeTicks = 0 Then Return Value.ToString("d") Else Return Value.ToString("G") End If End Function Public Shared Shadows Function ToString(Value As Decimal) As String Return Value.ToString("G") End Function Public Shared Shadows Function ToString(Value As Object) As String If Value Is Nothing Then Return Nothing Else Dim StringValue As String = TryCast(Value, String) If StringValue IsNot Nothing Then Return StringValue End If End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CStr(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CStr(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CStr(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CStr(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CStr(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CStr(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CStr(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CStr(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CStr(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CStr(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CStr(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CStr(DirectCast(Value, Double)) ElseIf TypeOf Value Is Char Then Return CStr(DirectCast(Value, Char)) ElseIf TypeOf Value Is Date Then Return CStr(DirectCast(Value, Date)) Else Dim CharArray As Char() = TryCast(Value, Char()) If CharArray IsNot Nothing Then Return New String(CharArray) End If End If Throw New Global.System.InvalidCastException() End Function Public Shared Shadows Function ToString(Value As Boolean) As String If Value Then Return Global.System.Boolean.TrueString Else Return Global.System.Boolean.FalseString End If End Function Public Shared Shadows Function ToString(Value As Byte) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Char) As String Return Value.ToString() End Function Friend Shared Function GetCultureInfo() As Global.System.Globalization.CultureInfo Return Global.System.Globalization.CultureInfo.CurrentCulture End Function Friend Shared Function ToHalfwidthNumbers(s As String, culture As Global.System.Globalization.CultureInfo) As String Return s End Function Friend Shared Function IsHexOrOctValue(Value As String, ByRef i64Value As Global.System.Int64) As Boolean Dim ch As Char Dim Length As Integer Dim FirstNonspace As Integer Dim TmpValue As String Length = Value.Length Do While (FirstNonspace < Length) ch = Value.Chars(FirstNonspace) If ch = "&"c AndAlso FirstNonspace + 2 < Length Then GoTo GetSpecialValue End If If ch <> Strings.ChrW(32) AndAlso ch <> Strings.ChrW(&H3000) Then Return False End If FirstNonspace += 1 Loop Return False GetSpecialValue: ch = Global.System.Char.ToLowerInvariant(Value.Chars(FirstNonspace + 1)) TmpValue = ToHalfwidthNumbers(Value.Substring(FirstNonspace + 2), GetCultureInfo()) If ch = "h"c Then i64Value = Global.System.Convert.ToInt64(TmpValue, 16) ElseIf ch = "o"c Then i64Value = Global.System.Convert.ToInt64(TmpValue, 8) Else Throw New Global.System.FormatException End If Return True End Function Friend Shared Function IsHexOrOctValue(Value As String, ByRef ui64Value As Global.System.UInt64) As Boolean Dim ch As Char Dim Length As Integer Dim FirstNonspace As Integer Dim TmpValue As String Length = Value.Length Do While (FirstNonspace < Length) ch = Value.Chars(FirstNonspace) If ch = "&"c AndAlso FirstNonspace + 2 < Length Then GoTo GetSpecialValue End If If ch <> Strings.ChrW(32) AndAlso ch <> Strings.ChrW(&H3000) Then Return False End If FirstNonspace += 1 Loop Return False GetSpecialValue: ch = Global.System.Char.ToLowerInvariant(Value.Chars(FirstNonspace + 1)) TmpValue = ToHalfwidthNumbers(Value.Substring(FirstNonspace + 2), GetCultureInfo()) If ch = "h"c Then ui64Value = Global.System.Convert.ToUInt64(TmpValue, 16) ElseIf ch = "o"c Then ui64Value = Global.System.Convert.ToUInt64(TmpValue, 8) Else Throw New Global.System.FormatException End If Return True End Function Public Shared Function ToGenericParameter(Of T)(Value As Object) As T If Value Is Nothing Then Return Nothing End If Dim reflectedType As Global.System.Type = GetType(T) If Global.System.Type.Equals(reflectedType, GetType(Global.System.Boolean)) Then Return DirectCast(CObj(CBool(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.SByte)) Then Return DirectCast(CObj(CSByte(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Byte)) Then Return DirectCast(CObj(CByte(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int16)) Then Return DirectCast(CObj(CShort(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt16)) Then Return DirectCast(CObj(CUShort(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int32)) Then Return DirectCast(CObj(CInt(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt32)) Then Return DirectCast(CObj(CUInt(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int64)) Then Return DirectCast(CObj(CLng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt64)) Then Return DirectCast(CObj(CULng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Decimal)) Then Return DirectCast(CObj(CDec(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Single)) Then Return DirectCast(CObj(CSng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Double)) Then Return DirectCast(CObj(CDbl(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.DateTime)) Then Return DirectCast(CObj(CDate(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Char)) Then Return DirectCast(CObj(CChar(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.String)) Then Return DirectCast(CObj(CStr(Value)), T) Else Return DirectCast(Value, T) End If End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class ProjectData Private Sub New() End Sub Public Overloads Shared Sub SetProjectError(ex As Global.System.Exception) End Sub Public Overloads Shared Sub SetProjectError(ex As Global.System.Exception, lErl As Integer) End Sub Public Shared Sub ClearProjectError() End Sub End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class Utils Private Sub New() End Sub Public Shared Function CopyArray(arySrc As Global.System.Array, aryDest As Global.System.Array) As Global.System.Array If arySrc Is Nothing Then Return aryDest End If Dim lLength As Integer lLength = arySrc.Length If lLength = 0 Then Return aryDest End If If aryDest.Rank() <> arySrc.Rank() Then Throw New Global.System.InvalidCastException() End If Dim iDim As Integer For iDim = 0 To aryDest.Rank() - 2 If aryDest.GetUpperBound(iDim) <> arySrc.GetUpperBound(iDim) Then Throw New Global.System.ArrayTypeMismatchException() End If Next iDim If lLength > aryDest.Length Then lLength = aryDest.Length End If If arySrc.Rank > 1 Then Dim LastRank As Integer = arySrc.Rank Dim lenSrcLastRank As Integer = arySrc.GetLength(LastRank - 1) Dim lenDestLastRank As Integer = aryDest.GetLength(LastRank - 1) If lenDestLastRank = 0 Then Return aryDest End If Dim lenCopy As Integer = If(lenSrcLastRank > lenDestLastRank, lenDestLastRank, lenSrcLastRank) Dim i As Integer For i = 0 To (arySrc.Length \ lenSrcLastRank) - 1 Global.System.Array.Copy(arySrc, i * lenSrcLastRank, aryDest, i * lenDestLastRank, lenCopy) Next i Else Global.System.Array.Copy(arySrc, aryDest, lLength) End If Return aryDest End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class ObjectFlowControl Friend NotInheritable Class ForLoopControl Public Shared Function ForNextCheckR4(count As Single, limit As Single, StepValue As Single) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function Public Shared Function ForNextCheckR8(count As Double, limit As Double, StepValue As Double) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function Public Shared Function ForNextCheckDec(count As Decimal, limit As Decimal, StepValue As Decimal) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function End Class End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class StaticLocalInitFlag Public State As Short End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class IncompleteInitialization Inherits Global.System.Exception Public Sub New() MyBase.New() End Sub End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class StandardModuleAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class DesignerGeneratedAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Parameter, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class OptionCompareAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class OptionTextAttribute Inherits Global.System.Attribute End Class End Namespace <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class HideModuleNameAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded(), Global.System.Diagnostics.DebuggerNonUserCode()> <Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute> Friend Module Strings Public Function ChrW(CharCode As Integer) As Char If CharCode < -32768 OrElse CharCode > 65535 Then Throw New Global.System.ArgumentException() End If Return Global.System.Convert.ToChar(CharCode And &HFFFFI) End Function Public Function AscW([String] As String) As Integer If ([String] Is Nothing) OrElse ([String].Length = 0) Then Throw New Global.System.ArgumentException() End If Return AscW([String].Chars(0)) End Function Public Function AscW([String] As Char) As Integer Return AscW([String]) End Function End Module <Global.Microsoft.VisualBasic.Embedded(), Global.System.Diagnostics.DebuggerNonUserCode()> <Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute> Friend Module Constants Public Const vbCrLf As String = ChrW(13) & ChrW(10) Public Const vbNewLine As String = ChrW(13) & ChrW(10) Public Const vbCr As String = ChrW(13) Public Const vbLf As String = ChrW(10) Public Const vbBack As String = ChrW(8) Public Const vbFormFeed As String = ChrW(12) Public Const vbTab As String = ChrW(9) Public Const vbVerticalTab As String = ChrW(11) Public Const vbNullChar As String = ChrW(0) Public Const vbNullString As String = Nothing End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict On Option Infer On Option Explicit On Option Compare Binary Namespace Global.Microsoft.VisualBasic Namespace CompilerServices <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class EmbeddedOperators Private Sub New() End Sub Public Shared Function CompareString(Left As String, Right As String, TextCompare As Boolean) As Integer If Left Is Right Then Return 0 End If If Left Is Nothing Then If Right.Length() = 0 Then Return 0 End If Return -1 End If If Right Is Nothing Then If Left.Length() = 0 Then Return 0 End If Return 1 End If Dim Result As Integer If TextCompare Then Dim OptionCompareTextFlags As Global.System.Globalization.CompareOptions = (Global.System.Globalization.CompareOptions.IgnoreCase Or Global.System.Globalization.CompareOptions.IgnoreWidth Or Global.System.Globalization.CompareOptions.IgnoreKanaType) Result = Conversions.GetCultureInfo().CompareInfo.Compare(Left, Right, OptionCompareTextFlags) Else Result = Global.System.String.CompareOrdinal(Left, Right) End If If Result = 0 Then Return 0 ElseIf Result > 0 Then Return 1 Else Return -1 End If End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class Conversions Private Sub New() End Sub Private Shared Function GetEnumValue(Value As Object) As Object Dim underlyingType = System.Enum.GetUnderlyingType(Value.GetType()) If underlyingType.Equals(GetType(SByte)) Then Return DirectCast(Value, SByte) ElseIf underlyingType.Equals(GetType(Byte)) Then Return DirectCast(Value, Byte) ElseIf underlyingType.Equals(GetType(Global.System.Int16)) Then Return DirectCast(Value, Global.System.Int16) ElseIf underlyingType.Equals(GetType(Global.System.UInt16)) Then Return DirectCast(Value, Global.System.UInt16) ElseIf underlyingType.Equals(GetType(Global.System.Int32)) Then Return DirectCast(Value, Global.System.Int32) ElseIf underlyingType.Equals(GetType(Global.System.UInt32)) Then Return DirectCast(Value, Global.System.UInt32) ElseIf underlyingType.Equals(GetType(Global.System.Int64)) Then Return DirectCast(Value, Global.System.Int64) ElseIf underlyingType.Equals(GetType(Global.System.UInt64)) Then Return DirectCast(Value, Global.System.UInt64) Else Throw New Global.System.InvalidCastException End If End Function Public Shared Function ToBoolean(Value As String) As Boolean If Value Is Nothing Then Value = "" End If Try Dim loc As Global.System.Globalization.CultureInfo = GetCultureInfo() If loc.CompareInfo.Compare(Value, Boolean.FalseString, Global.System.Globalization.CompareOptions.IgnoreCase) = 0 Then Return False ElseIf loc.CompareInfo.Compare(Value, Boolean.TrueString, Global.System.Globalization.CompareOptions.IgnoreCase) = 0 Then Return True End If Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CBool(i64Value) End If Return CBool(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToBoolean(Value As Object) As Boolean If Value Is Nothing Then Return False End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CBool(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CBool(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CBool(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CBool(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CBool(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CBool(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CBool(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CBool(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CBool(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CBool(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CBool(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CBool(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CBool(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToByte(Value As String) As Byte If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CByte(i64Value) End If Return CByte(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToByte(Value As Object) As Byte If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CByte(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CByte(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CByte(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CByte(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CByte(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CByte(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CByte(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CByte(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CByte(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CByte(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CByte(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CByte(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CByte(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToSByte(Value As String) As SByte If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CSByte(i64Value) End If Return CSByte(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToSByte(Value As Object) As SByte If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CSByte(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CSByte(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CSByte(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CSByte(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CSByte(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CSByte(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CSByte(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CSByte(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CSByte(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CSByte(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CSByte(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CSByte(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CSByte(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToShort(Value As String) As Short If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CShort(i64Value) End If Return CShort(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToShort(Value As Object) As Short If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CShort(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CShort(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CShort(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CShort(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CShort(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CShort(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CShort(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CShort(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CShort(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CShort(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CShort(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CShort(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CShort(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUShort(Value As String) As UShort If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CUShort(i64Value) End If Return CUShort(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUShort(Value As Object) As UShort If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CUShort(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CUShort(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CUShort(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CUShort(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CUShort(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CUShort(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CUShort(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CUShort(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CUShort(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CUShort(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CUShort(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CUShort(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CUShort(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToInteger(Value As String) As Integer If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CInt(i64Value) End If Return CInt(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToInteger(Value As Object) As Integer If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CInt(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CInt(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CInt(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CInt(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CInt(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CInt(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CInt(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CInt(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CInt(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CInt(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CInt(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CInt(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CInt(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUInteger(Value As String) As UInteger If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CUInt(i64Value) End If Return CUInt(ParseDouble(Value)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToUInteger(Value As Object) As UInteger If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CUInt(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CUInt(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CUInt(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CUInt(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CUInt(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CUInt(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CUInt(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CUInt(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CUInt(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CUInt(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CUInt(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CUInt(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CUInt(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToLong(Value As String) As Long If (Value Is Nothing) Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CLng(i64Value) End If Return CLng(ParseDecimal(Value, Nothing)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToLong(Value As Object) As Long If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CLng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CLng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CLng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CLng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CLng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CLng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CLng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CLng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CLng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CLng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CLng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CLng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CLng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function <Global.System.CLSCompliant(False)> Public Shared Function ToULong(Value As String) As ULong If (Value Is Nothing) Then Return 0 End If Try Dim ui64Value As Global.System.UInt64 If IsHexOrOctValue(Value, ui64Value) Then Return CULng(ui64Value) End If Return CULng(ParseDecimal(Value, Nothing)) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function <Global.System.CLSCompliant(False)> Public Shared Function ToULong(Value As Object) As ULong If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CULng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CULng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CULng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CULng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CULng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CULng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CULng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CULng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CULng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CULng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CULng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CULng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CULng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToDecimal(Value As Boolean) As Decimal If Value Then Return -1D Else Return 0D End If End Function Public Shared Function ToDecimal(Value As String) As Decimal If Value Is Nothing Then Return 0D End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CDec(i64Value) End If Return ParseDecimal(Value, Nothing) Catch e1 As Global.System.OverflowException Throw e1 Catch e2 As Global.System.FormatException Throw New Global.System.InvalidCastException(e2.Message, e2) End Try End Function Public Shared Function ToDecimal(Value As Object) As Decimal If Value Is Nothing Then Return 0D End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CDec(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CDec(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CDec(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CDec(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CDec(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CDec(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CDec(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CDec(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CDec(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CDec(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CDec(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CDec(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CDec(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Private Shared Function ParseDecimal(Value As String, NumberFormat As Global.System.Globalization.NumberFormatInfo) As Decimal Dim NormalizedNumberFormat As Global.System.Globalization.NumberFormatInfo Dim culture As Global.System.Globalization.CultureInfo = GetCultureInfo() If NumberFormat Is Nothing Then NumberFormat = culture.NumberFormat End If NormalizedNumberFormat = GetNormalizedNumberFormat(NumberFormat) Const flags As Global.System.Globalization.NumberStyles = Global.System.Globalization.NumberStyles.AllowDecimalPoint Or Global.System.Globalization.NumberStyles.AllowExponent Or Global.System.Globalization.NumberStyles.AllowLeadingSign Or Global.System.Globalization.NumberStyles.AllowLeadingWhite Or Global.System.Globalization.NumberStyles.AllowThousands Or Global.System.Globalization.NumberStyles.AllowTrailingSign Or Global.System.Globalization.NumberStyles.AllowParentheses Or Global.System.Globalization.NumberStyles.AllowTrailingWhite Or Global.System.Globalization.NumberStyles.AllowCurrencySymbol Value = ToHalfwidthNumbers(Value, culture) Try Return Global.System.Decimal.Parse(Value, flags, NormalizedNumberFormat) Catch FormatEx As Global.System.FormatException When Not (NumberFormat Is NormalizedNumberFormat) Return Global.System.Decimal.Parse(Value, flags, NumberFormat) Catch Ex As Global.System.Exception Throw Ex End Try End Function Private Shared Function GetNormalizedNumberFormat(InNumberFormat As Global.System.Globalization.NumberFormatInfo) As Global.System.Globalization.NumberFormatInfo Dim OutNumberFormat As Global.System.Globalization.NumberFormatInfo With InNumberFormat If (Not .CurrencyDecimalSeparator Is Nothing) AndAlso (Not .NumberDecimalSeparator Is Nothing) AndAlso (Not .CurrencyGroupSeparator Is Nothing) AndAlso (Not .NumberGroupSeparator Is Nothing) AndAlso (.CurrencyDecimalSeparator.Length = 1) AndAlso (.NumberDecimalSeparator.Length = 1) AndAlso (.CurrencyGroupSeparator.Length = 1) AndAlso (.NumberGroupSeparator.Length = 1) AndAlso (.CurrencyDecimalSeparator.Chars(0) = .NumberDecimalSeparator.Chars(0)) AndAlso (.CurrencyGroupSeparator.Chars(0) = .NumberGroupSeparator.Chars(0)) AndAlso (.CurrencyDecimalDigits = .NumberDecimalDigits) Then Return InNumberFormat End If End With With InNumberFormat If (Not .CurrencyDecimalSeparator Is Nothing) AndAlso (Not .NumberDecimalSeparator Is Nothing) AndAlso (.CurrencyDecimalSeparator.Length = .NumberDecimalSeparator.Length) AndAlso (Not .CurrencyGroupSeparator Is Nothing) AndAlso (Not .NumberGroupSeparator Is Nothing) AndAlso (.CurrencyGroupSeparator.Length = .NumberGroupSeparator.Length) Then Dim i As Integer For i = 0 To .CurrencyDecimalSeparator.Length - 1 If (.CurrencyDecimalSeparator.Chars(i) <> .NumberDecimalSeparator.Chars(i)) Then GoTo MisMatch Next For i = 0 To .CurrencyGroupSeparator.Length - 1 If (.CurrencyGroupSeparator.Chars(i) <> .NumberGroupSeparator.Chars(i)) Then GoTo MisMatch Next Return InNumberFormat End If End With MisMatch: OutNumberFormat = DirectCast(InNumberFormat.Clone, Global.System.Globalization.NumberFormatInfo) With OutNumberFormat .CurrencyDecimalSeparator = .NumberDecimalSeparator .CurrencyGroupSeparator = .NumberGroupSeparator .CurrencyDecimalDigits = .NumberDecimalDigits End With Return OutNumberFormat End Function Public Shared Function ToSingle(Value As String) As Single If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CSng(i64Value) End If Dim Result As Double = ParseDouble(Value) If (Result < Global.System.Single.MinValue OrElse Result > Global.System.Single.MaxValue) AndAlso Not Global.System.Double.IsInfinity(Result) Then Throw New Global.System.OverflowException End If Return CSng(Result) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToSingle(Value As Object) As Single If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CSng(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CSng(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CSng(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CSng(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CSng(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CSng(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CSng(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CSng(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CSng(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CSng(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CSng(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CSng(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CSng(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToDouble(Value As String) As Double If Value Is Nothing Then Return 0 End If Try Dim i64Value As Global.System.Int64 If IsHexOrOctValue(Value, i64Value) Then Return CDbl(i64Value) End If Return ParseDouble(Value) Catch e As Global.System.FormatException Throw New Global.System.InvalidCastException(e.Message, e) End Try End Function Public Shared Function ToDouble(Value As Object) As Double If Value Is Nothing Then Return 0 End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CDbl(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CDbl(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CDbl(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CDbl(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CDbl(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CDbl(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CDbl(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CDbl(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CDbl(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CDbl(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CDbl(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CDbl(DirectCast(Value, Double)) ElseIf TypeOf Value Is String Then Return CDbl(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Private Shared Function ParseDouble(Value As String) As Double Dim NormalizedNumberFormat As Global.System.Globalization.NumberFormatInfo Dim culture As Global.System.Globalization.CultureInfo = GetCultureInfo() Dim NumberFormat As Global.System.Globalization.NumberFormatInfo = culture.NumberFormat NormalizedNumberFormat = GetNormalizedNumberFormat(NumberFormat) Const flags As Global.System.Globalization.NumberStyles = Global.System.Globalization.NumberStyles.AllowDecimalPoint Or Global.System.Globalization.NumberStyles.AllowExponent Or Global.System.Globalization.NumberStyles.AllowLeadingSign Or Global.System.Globalization.NumberStyles.AllowLeadingWhite Or Global.System.Globalization.NumberStyles.AllowThousands Or Global.System.Globalization.NumberStyles.AllowTrailingSign Or Global.System.Globalization.NumberStyles.AllowParentheses Or Global.System.Globalization.NumberStyles.AllowTrailingWhite Or Global.System.Globalization.NumberStyles.AllowCurrencySymbol Value = ToHalfwidthNumbers(Value, culture) Try Return Global.System.Double.Parse(Value, flags, NormalizedNumberFormat) Catch FormatEx As Global.System.FormatException When Not (NumberFormat Is NormalizedNumberFormat) Return Global.System.Double.Parse(Value, flags, NumberFormat) Catch Ex As Global.System.Exception Throw Ex End Try End Function Public Shared Function ToDate(Value As String) As Date Dim ParsedDate As Global.System.DateTime Const ParseStyle As Global.System.Globalization.DateTimeStyles = Global.System.Globalization.DateTimeStyles.AllowWhiteSpaces Or Global.System.Globalization.DateTimeStyles.NoCurrentDateDefault Dim Culture As Global.System.Globalization.CultureInfo = GetCultureInfo() Dim result = Global.System.DateTime.TryParse(ToHalfwidthNumbers(Value, Culture), Culture, ParseStyle, ParsedDate) If result Then Return ParsedDate Else Throw New Global.System.InvalidCastException() End If End Function Public Shared Function ToDate(Value As Object) As Date If Value Is Nothing Then Return Nothing End If If TypeOf Value Is Global.System.DateTime Then Return CDate(DirectCast(Value, Global.System.DateTime)) ElseIf TypeOf Value Is String Then Return CDate(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToChar(Value As String) As Char If (Value Is Nothing) OrElse (Value.Length = 0) Then Return Global.System.Convert.ToChar(0 And &HFFFFI) End If Return Value.Chars(0) End Function Public Shared Function ToChar(Value As Object) As Char If Value Is Nothing Then Return Global.System.Convert.ToChar(0 And &HFFFFI) End If If TypeOf Value Is Char Then Return CChar(DirectCast(Value, Char)) ElseIf TypeOf Value Is String Then Return CChar(DirectCast(Value, String)) End If Throw New Global.System.InvalidCastException() End Function Public Shared Function ToCharArrayRankOne(Value As String) As Char() If Value Is Nothing Then Value = "" End If Return Value.ToCharArray() End Function Public Shared Function ToCharArrayRankOne(Value As Object) As Char() If Value Is Nothing Then Return "".ToCharArray() End If Dim ArrayValue As Char() = TryCast(Value, Char()) If ArrayValue IsNot Nothing AndAlso ArrayValue.Rank = 1 Then Return ArrayValue ElseIf TypeOf Value Is String Then Return DirectCast(Value, String).ToCharArray() End If Throw New Global.System.InvalidCastException() End Function Public Shared Shadows Function ToString(Value As Short) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Integer) As String Return Value.ToString() End Function <Global.System.CLSCompliant(False)> Public Shared Shadows Function ToString(Value As UInteger) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Long) As String Return Value.ToString() End Function <Global.System.CLSCompliant(False)> Public Shared Shadows Function ToString(Value As ULong) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Single) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Double) As String Return Value.ToString("G") End Function Public Shared Shadows Function ToString(Value As Date) As String Dim TimeTicks As Long = Value.TimeOfDay.Ticks If (TimeTicks = Value.Ticks) OrElse (Value.Year = 1899 AndAlso Value.Month = 12 AndAlso Value.Day = 30) Then Return Value.ToString("T") ElseIf TimeTicks = 0 Then Return Value.ToString("d") Else Return Value.ToString("G") End If End Function Public Shared Shadows Function ToString(Value As Decimal) As String Return Value.ToString("G") End Function Public Shared Shadows Function ToString(Value As Object) As String If Value Is Nothing Then Return Nothing Else Dim StringValue As String = TryCast(Value, String) If StringValue IsNot Nothing Then Return StringValue End If End If If TypeOf Value Is Global.System.Enum Then Value = GetEnumValue(Value) End If If TypeOf Value Is Boolean Then Return CStr(DirectCast(Value, Boolean)) ElseIf TypeOf Value Is SByte Then Return CStr(DirectCast(Value, SByte)) ElseIf TypeOf Value Is Byte Then Return CStr(DirectCast(Value, Byte)) ElseIf TypeOf Value Is Global.System.Int16 Then Return CStr(DirectCast(Value, Global.System.Int16)) ElseIf TypeOf Value Is Global.System.UInt16 Then Return CStr(DirectCast(Value, Global.System.UInt16)) ElseIf TypeOf Value Is Global.System.Int32 Then Return CStr(DirectCast(Value, Global.System.Int32)) ElseIf TypeOf Value Is Global.System.UInt32 Then Return CStr(DirectCast(Value, Global.System.UInt32)) ElseIf TypeOf Value Is Global.System.Int64 Then Return CStr(DirectCast(Value, Global.System.Int64)) ElseIf TypeOf Value Is Global.System.UInt64 Then Return CStr(DirectCast(Value, Global.System.UInt64)) ElseIf TypeOf Value Is Decimal Then Return CStr(DirectCast(Value, Global.System.Decimal)) ElseIf TypeOf Value Is Single Then Return CStr(DirectCast(Value, Single)) ElseIf TypeOf Value Is Double Then Return CStr(DirectCast(Value, Double)) ElseIf TypeOf Value Is Char Then Return CStr(DirectCast(Value, Char)) ElseIf TypeOf Value Is Date Then Return CStr(DirectCast(Value, Date)) Else Dim CharArray As Char() = TryCast(Value, Char()) If CharArray IsNot Nothing Then Return New String(CharArray) End If End If Throw New Global.System.InvalidCastException() End Function Public Shared Shadows Function ToString(Value As Boolean) As String If Value Then Return Global.System.Boolean.TrueString Else Return Global.System.Boolean.FalseString End If End Function Public Shared Shadows Function ToString(Value As Byte) As String Return Value.ToString() End Function Public Shared Shadows Function ToString(Value As Char) As String Return Value.ToString() End Function Friend Shared Function GetCultureInfo() As Global.System.Globalization.CultureInfo Return Global.System.Globalization.CultureInfo.CurrentCulture End Function Friend Shared Function ToHalfwidthNumbers(s As String, culture As Global.System.Globalization.CultureInfo) As String Return s End Function Friend Shared Function IsHexOrOctValue(Value As String, ByRef i64Value As Global.System.Int64) As Boolean Dim ch As Char Dim Length As Integer Dim FirstNonspace As Integer Dim TmpValue As String Length = Value.Length Do While (FirstNonspace < Length) ch = Value.Chars(FirstNonspace) If ch = "&"c AndAlso FirstNonspace + 2 < Length Then GoTo GetSpecialValue End If If ch <> Strings.ChrW(32) AndAlso ch <> Strings.ChrW(&H3000) Then Return False End If FirstNonspace += 1 Loop Return False GetSpecialValue: ch = Global.System.Char.ToLowerInvariant(Value.Chars(FirstNonspace + 1)) TmpValue = ToHalfwidthNumbers(Value.Substring(FirstNonspace + 2), GetCultureInfo()) If ch = "h"c Then i64Value = Global.System.Convert.ToInt64(TmpValue, 16) ElseIf ch = "o"c Then i64Value = Global.System.Convert.ToInt64(TmpValue, 8) Else Throw New Global.System.FormatException End If Return True End Function Friend Shared Function IsHexOrOctValue(Value As String, ByRef ui64Value As Global.System.UInt64) As Boolean Dim ch As Char Dim Length As Integer Dim FirstNonspace As Integer Dim TmpValue As String Length = Value.Length Do While (FirstNonspace < Length) ch = Value.Chars(FirstNonspace) If ch = "&"c AndAlso FirstNonspace + 2 < Length Then GoTo GetSpecialValue End If If ch <> Strings.ChrW(32) AndAlso ch <> Strings.ChrW(&H3000) Then Return False End If FirstNonspace += 1 Loop Return False GetSpecialValue: ch = Global.System.Char.ToLowerInvariant(Value.Chars(FirstNonspace + 1)) TmpValue = ToHalfwidthNumbers(Value.Substring(FirstNonspace + 2), GetCultureInfo()) If ch = "h"c Then ui64Value = Global.System.Convert.ToUInt64(TmpValue, 16) ElseIf ch = "o"c Then ui64Value = Global.System.Convert.ToUInt64(TmpValue, 8) Else Throw New Global.System.FormatException End If Return True End Function Public Shared Function ToGenericParameter(Of T)(Value As Object) As T If Value Is Nothing Then Return Nothing End If Dim reflectedType As Global.System.Type = GetType(T) If Global.System.Type.Equals(reflectedType, GetType(Global.System.Boolean)) Then Return DirectCast(CObj(CBool(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.SByte)) Then Return DirectCast(CObj(CSByte(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Byte)) Then Return DirectCast(CObj(CByte(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int16)) Then Return DirectCast(CObj(CShort(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt16)) Then Return DirectCast(CObj(CUShort(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int32)) Then Return DirectCast(CObj(CInt(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt32)) Then Return DirectCast(CObj(CUInt(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Int64)) Then Return DirectCast(CObj(CLng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.UInt64)) Then Return DirectCast(CObj(CULng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Decimal)) Then Return DirectCast(CObj(CDec(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Single)) Then Return DirectCast(CObj(CSng(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Double)) Then Return DirectCast(CObj(CDbl(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.DateTime)) Then Return DirectCast(CObj(CDate(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.Char)) Then Return DirectCast(CObj(CChar(Value)), T) ElseIf Global.System.Type.Equals(reflectedType, GetType(Global.System.String)) Then Return DirectCast(CObj(CStr(Value)), T) Else Return DirectCast(Value, T) End If End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class ProjectData Private Sub New() End Sub Public Overloads Shared Sub SetProjectError(ex As Global.System.Exception) End Sub Public Overloads Shared Sub SetProjectError(ex As Global.System.Exception, lErl As Integer) End Sub Public Shared Sub ClearProjectError() End Sub End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class Utils Private Sub New() End Sub Public Shared Function CopyArray(arySrc As Global.System.Array, aryDest As Global.System.Array) As Global.System.Array If arySrc Is Nothing Then Return aryDest End If Dim lLength As Integer lLength = arySrc.Length If lLength = 0 Then Return aryDest End If If aryDest.Rank() <> arySrc.Rank() Then Throw New Global.System.InvalidCastException() End If Dim iDim As Integer For iDim = 0 To aryDest.Rank() - 2 If aryDest.GetUpperBound(iDim) <> arySrc.GetUpperBound(iDim) Then Throw New Global.System.ArrayTypeMismatchException() End If Next iDim If lLength > aryDest.Length Then lLength = aryDest.Length End If If arySrc.Rank > 1 Then Dim LastRank As Integer = arySrc.Rank Dim lenSrcLastRank As Integer = arySrc.GetLength(LastRank - 1) Dim lenDestLastRank As Integer = aryDest.GetLength(LastRank - 1) If lenDestLastRank = 0 Then Return aryDest End If Dim lenCopy As Integer = If(lenSrcLastRank > lenDestLastRank, lenDestLastRank, lenSrcLastRank) Dim i As Integer For i = 0 To (arySrc.Length \ lenSrcLastRank) - 1 Global.System.Array.Copy(arySrc, i * lenSrcLastRank, aryDest, i * lenDestLastRank, lenCopy) Next i Else Global.System.Array.Copy(arySrc, aryDest, lLength) End If Return aryDest End Function End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class ObjectFlowControl Friend NotInheritable Class ForLoopControl Public Shared Function ForNextCheckR4(count As Single, limit As Single, StepValue As Single) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function Public Shared Function ForNextCheckR8(count As Double, limit As Double, StepValue As Double) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function Public Shared Function ForNextCheckDec(count As Decimal, limit As Decimal, StepValue As Decimal) As Boolean If StepValue >= 0 Then Return count <= limit Else Return count >= limit End If End Function End Class End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class StaticLocalInitFlag Public State As Short End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.Diagnostics.DebuggerNonUserCode(), Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Friend NotInheritable Class IncompleteInitialization Inherits Global.System.Exception Public Sub New() MyBase.New() End Sub End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class StandardModuleAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class DesignerGeneratedAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Parameter, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class OptionCompareAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class OptionTextAttribute Inherits Global.System.Attribute End Class End Namespace <Global.Microsoft.VisualBasic.Embedded()> <Global.System.AttributeUsage(Global.System.AttributeTargets.Class, Inherited:=False)> <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> <Global.System.Runtime.CompilerServices.CompilerGenerated()> Friend NotInheritable Class HideModuleNameAttribute Inherits Global.System.Attribute End Class <Global.Microsoft.VisualBasic.Embedded(), Global.System.Diagnostics.DebuggerNonUserCode()> <Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute> Friend Module Strings Public Function ChrW(CharCode As Integer) As Char If CharCode < -32768 OrElse CharCode > 65535 Then Throw New Global.System.ArgumentException() End If Return Global.System.Convert.ToChar(CharCode And &HFFFFI) End Function Public Function AscW([String] As String) As Integer If ([String] Is Nothing) OrElse ([String].Length = 0) Then Throw New Global.System.ArgumentException() End If Return AscW([String].Chars(0)) End Function Public Function AscW([String] As Char) As Integer Return AscW([String]) End Function End Module <Global.Microsoft.VisualBasic.Embedded(), Global.System.Diagnostics.DebuggerNonUserCode()> <Global.System.Runtime.CompilerServices.CompilerGenerated()> <Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute> Friend Module Constants Public Const vbCrLf As String = ChrW(13) & ChrW(10) Public Const vbNewLine As String = ChrW(13) & ChrW(10) Public Const vbCr As String = ChrW(13) Public Const vbLf As String = ChrW(10) Public Const vbBack As String = ChrW(8) Public Const vbFormFeed As String = ChrW(12) Public Const vbTab As String = ChrW(9) Public Const vbVerticalTab As String = ChrW(11) Public Const vbNullChar As String = ChrW(0) Public Const vbNullString As String = Nothing End Module End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class MiscellaneousTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DoesNothingOnEmptyFile() VerifyStatementEndConstructNotApplied( text:="", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DoesNothingOnFileWithNoStatement() VerifyStatementEndConstructNotApplied( text:="'Goo ", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyLineContinuationMark() VerifyStatementEndConstructNotApplied( text:="Class C function f(byval x as Integer, byref y as string) as string for i = 1 to 10 _ return y End Function End Class", caret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplicitLineContinuation() VerifyStatementEndConstructNotApplied( text:="Class C function f() as string While 1 + return y End Function End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyNestedDo() VerifyStatementEndConstructApplied( before:="Class C function f() as string for i = 1 to 10", beforeCaret:={2, -1}, after:="Class C function f() as string for i = 1 to 10 Next", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyMultilinesChar() VerifyStatementEndConstructApplied( before:="Class C sub s do :do Loop End sub End Class", beforeCaret:={2, -1}, after:="Class C sub s do :do Loop Loop End sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyInlineComments() VerifyStatementEndConstructApplied( before:="Class C sub s If true then 'here End sub End Class", beforeCaret:={2, -1}, after:="Class C sub s If true then 'here End If End sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNotAppliedWithJunkAtEndOfLine() ' Try this without a newline at the end of the file VerifyStatementEndConstructNotApplied( text:="Class C End Class", caret:={0, "Class C".Length}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNotAppliedWithJunkAtEndOfLine2() ' Try this with a newline at the end of the file VerifyStatementEndConstructNotApplied( text:="Class C End Class ", caret:={0, "Class C".Length}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> <WorkItem(539727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539727")> Public Sub DeletesSelectedText() Using workspace = TestWorkspace.CreateVisualBasic("Interface IGoo ~~") Dim textView = workspace.Documents.Single().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() ' Select the ~~ backwards, so the caret location is at the start Dim startPoint = New SnapshotPoint(textView.TextSnapshot, textView.TextSnapshot.Length - 2) textView.TryMoveCaretToAndEnsureVisible(startPoint) textView.SetSelection(New SnapshotSpan(startPoint, length:=2)) Dim endConstructService As New VisualBasicEndConstructService( workspace.GetService(Of ISmartIndentationService), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.True(endConstructService.TryDoEndConstructForEnterKey(textView, textView.TextSnapshot.TextBuffer, CancellationToken.None)) Assert.Equal("End Interface", textView.TextSnapshot.Lines.Last().GetText()) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class MiscellaneousTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DoesNothingOnEmptyFile() VerifyStatementEndConstructNotApplied( text:="", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DoesNothingOnFileWithNoStatement() VerifyStatementEndConstructNotApplied( text:="'Goo ", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyLineContinuationMark() VerifyStatementEndConstructNotApplied( text:="Class C function f(byval x as Integer, byref y as string) as string for i = 1 to 10 _ return y End Function End Class", caret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplicitLineContinuation() VerifyStatementEndConstructNotApplied( text:="Class C function f() as string While 1 + return y End Function End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyNestedDo() VerifyStatementEndConstructApplied( before:="Class C function f() as string for i = 1 to 10", beforeCaret:={2, -1}, after:="Class C function f() as string for i = 1 to 10 Next", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyMultilinesChar() VerifyStatementEndConstructApplied( before:="Class C sub s do :do Loop End sub End Class", beforeCaret:={2, -1}, after:="Class C sub s do :do Loop Loop End sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyInlineComments() VerifyStatementEndConstructApplied( before:="Class C sub s If true then 'here End sub End Class", beforeCaret:={2, -1}, after:="Class C sub s If true then 'here End If End sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNotAppliedWithJunkAtEndOfLine() ' Try this without a newline at the end of the file VerifyStatementEndConstructNotApplied( text:="Class C End Class", caret:={0, "Class C".Length}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNotAppliedWithJunkAtEndOfLine2() ' Try this with a newline at the end of the file VerifyStatementEndConstructNotApplied( text:="Class C End Class ", caret:={0, "Class C".Length}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> <WorkItem(539727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539727")> Public Sub DeletesSelectedText() Using workspace = TestWorkspace.CreateVisualBasic("Interface IGoo ~~") Dim textView = workspace.Documents.Single().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() ' Select the ~~ backwards, so the caret location is at the start Dim startPoint = New SnapshotPoint(textView.TextSnapshot, textView.TextSnapshot.Length - 2) textView.TryMoveCaretToAndEnsureVisible(startPoint) textView.SetSelection(New SnapshotSpan(startPoint, length:=2)) Dim endConstructService As New VisualBasicEndConstructService( workspace.GetService(Of ISmartIndentationService), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.True(endConstructService.TryDoEndConstructForEnterKey(textView, textView.TextSnapshot.TextBuffer, CancellationToken.None)) Assert.Equal("End Interface", textView.TextSnapshot.Lines.Last().GetText()) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.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="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診断</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="ja" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診断</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/TypeImportCompletionServiceFactory.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportLanguageServiceFactory(GetType(ITypeImportCompletionService), LanguageNames.VisualBasic), [Shared]> Friend NotInheritable Class TypeImportCompletionServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New BasicTypeImportCompletionService(languageServices.WorkspaceServices.Workspace) End Function Private Class BasicTypeImportCompletionService Inherits AbstractTypeImportCompletionService Public Sub New(workspace As Workspace) MyBase.New(workspace) End Sub Protected Overrides ReadOnly Property GenericTypeSuffix As String Get Return "(Of ...)" End Get End Property Protected Overrides ReadOnly Property IsCaseSensitive As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property 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.Composition Imports Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportLanguageServiceFactory(GetType(ITypeImportCompletionService), LanguageNames.VisualBasic), [Shared]> Friend NotInheritable Class TypeImportCompletionServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New BasicTypeImportCompletionService(languageServices.WorkspaceServices.Workspace) End Function Private Class BasicTypeImportCompletionService Inherits AbstractTypeImportCompletionService Public Sub New(workspace As Workspace) MyBase.New(workspace) End Sub Protected Overrides ReadOnly Property GenericTypeSuffix As String Get Return "(Of ...)" End Get End Property Protected Overrides ReadOnly Property IsCaseSensitive As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/CoreTest/SyntaxReferenceTests.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.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class SyntaxReferenceTests : TestBase { private static Workspace CreateWorkspace(Type[] additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); private static Workspace CreateWorkspaceWithRecoverableSyntaxTrees() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } private static Solution AddSingleFileCSharpProject(Solution solution, string source) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); return solution .AddProject(pid, "Test", "Test.dll", LanguageNames.CSharp) .AddDocument(did, "Test.cs", SourceText.From(source)); } private static Solution AddSingleFileVisualBasicProject(Solution solution, string source) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); return solution .AddProject(pid, "Test", "Test.dll", LanguageNames.VisualBasic) .AddDocument(did, "Test.vb", SourceText.From(source)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToZeroWidthNode() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" public class C<> { } "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it) var node = tree.GetRoot().DescendantNodes().OfType<CS.Syntax.TypeParameterSyntax>().Single(); Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestVisualBasicReferenceToZeroWidthNode() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" Public Class C(Of ) End Class "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it) var node = tree.GetRoot().DescendantNodes().OfType<VB.Syntax.TypeParameterSyntax>().Single(); Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" #if true || true public class C { } #endif "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First(); var syntaxRef = tree.GetReference(node); Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestVisualBasicReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" #If True Or True Then Public Class C End Class #End If "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First(); var syntaxRef = tree.GetReference(node); Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToZeroWidthNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" #if true || public class C { } #endif "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First(); // right side should be missing identifier name syntax var node = binary.Right; Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public async System.Threading.Tasks.Task TestVisualBasicReferenceToZeroWidthNodeInStructuredTriviaAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" #If (True Or ) Then Public Class C End Class #End If "); var tree = await solution.Projects.First().Documents.First().GetSyntaxTreeAsync(); // find binary node that is part of #if directive var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First(); // right side should be missing identifier name syntax var node = binary.Right; Assert.True(node.IsMissing); Assert.Equal(0, node.Span.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } } }
// Licensed to the .NET Foundation under one or more 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.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class SyntaxReferenceTests : TestBase { private static Workspace CreateWorkspace(Type[] additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); private static Workspace CreateWorkspaceWithRecoverableSyntaxTrees() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } private static Solution AddSingleFileCSharpProject(Solution solution, string source) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); return solution .AddProject(pid, "Test", "Test.dll", LanguageNames.CSharp) .AddDocument(did, "Test.cs", SourceText.From(source)); } private static Solution AddSingleFileVisualBasicProject(Solution solution, string source) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); return solution .AddProject(pid, "Test", "Test.dll", LanguageNames.VisualBasic) .AddDocument(did, "Test.vb", SourceText.From(source)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToZeroWidthNode() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" public class C<> { } "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it) var node = tree.GetRoot().DescendantNodes().OfType<CS.Syntax.TypeParameterSyntax>().Single(); Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestVisualBasicReferenceToZeroWidthNode() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" Public Class C(Of ) End Class "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // this is an expected TypeParameterSyntax with a missing identifier token (it is zero-length w/ an error attached to it) var node = tree.GetRoot().DescendantNodes().OfType<VB.Syntax.TypeParameterSyntax>().Single(); Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" #if true || true public class C { } #endif "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First(); var syntaxRef = tree.GetReference(node); Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestVisualBasicReferenceToNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" #If True Or True Then Public Class C End Class #End If "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var node = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First(); var syntaxRef = tree.GetReference(node); Assert.Equal("PositionalSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestCSharpReferenceToZeroWidthNodeInStructuredTrivia() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileCSharpProject(workspace.CurrentSolution, @" #if true || public class C { } #endif "); var tree = solution.Projects.First().Documents.First().GetSyntaxTreeAsync().Result; // find binary node that is part of #if directive var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<CS.Syntax.BinaryExpressionSyntax>().First(); // right side should be missing identifier name syntax var node = binary.Right; Assert.Equal(0, node.FullSpan.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public async System.Threading.Tasks.Task TestVisualBasicReferenceToZeroWidthNodeInStructuredTriviaAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTrees(); var solution = AddSingleFileVisualBasicProject(workspace.CurrentSolution, @" #If (True Or ) Then Public Class C End Class #End If "); var tree = await solution.Projects.First().Documents.First().GetSyntaxTreeAsync(); // find binary node that is part of #if directive var binary = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<VB.Syntax.BinaryExpressionSyntax>().First(); // right side should be missing identifier name syntax var node = binary.Right; Assert.True(node.IsMissing); Assert.Equal(0, node.Span.Length); var syntaxRef = tree.GetReference(node); Assert.Equal("PathSyntaxReference", syntaxRef.GetType().Name); var refNode = syntaxRef.GetSyntax(); Assert.Equal(node, refNode); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Binder/ForLoopBinder.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class ForLoopBinder : LoopBinder { private readonly ForStatementSyntax _syntax; public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (var vdecl in _syntax.Declaration.Variables) { var localSymbol = MakeLocal(_syntax.Declaration, vdecl, LocalDeclarationKind.RegularVariable); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl); } } else { ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Initializers); } return locals.ToImmutableAndFree(); } internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForStatement result = BindForParts(_syntax, originalBinder, diagnostics); return result; } private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray<LocalSymbol>.Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.BindStatementExpressionList(incrementors, diagnostics); Debug.Assert(increment.Kind != BoundKind.StatementList || ((BoundStatementList)increment).Statements.Length > 1); var locals = incrementBinder.GetDeclaredLocalsForScope(scopeDesignator); if (!locals.IsEmpty) { if (increment.Kind == BoundKind.StatementList) { increment = new BoundBlock(scopeDesignator, locals, ((BoundStatementList)increment).Statements) { WasCompilerGenerated = true }; } else { increment = new BoundBlock(increment.Syntax, locals, ImmutableArray.Create(increment)) { WasCompilerGenerated = true }; } } } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel); } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
// Licensed to the .NET Foundation under one or more 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class ForLoopBinder : LoopBinder { private readonly ForStatementSyntax _syntax; public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (var vdecl in _syntax.Declaration.Variables) { var localSymbol = MakeLocal(_syntax.Declaration, vdecl, LocalDeclarationKind.RegularVariable); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl); } } else { ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Initializers); } return locals.ToImmutableAndFree(); } internal override BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForStatement result = BindForParts(_syntax, originalBinder, diagnostics); return result; } private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray<LocalSymbol>.Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.BindStatementExpressionList(incrementors, diagnostics); Debug.Assert(increment.Kind != BoundKind.StatementList || ((BoundStatementList)increment).Statements.Length > 1); var locals = incrementBinder.GetDeclaredLocalsForScope(scopeDesignator); if (!locals.IsEmpty) { if (increment.Kind == BoundKind.StatementList) { increment = new BoundBlock(scopeDesignator, locals, ((BoundStatementList)increment).Statements) { WasCompilerGenerated = true }; } else { increment = new BoundBlock(increment.Syntax, locals, ImmutableArray.Create(increment)) { WasCompilerGenerated = true }; } } } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel); } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./azure-pipelines-pr-validation.yml
resources: - repo: self clean: true # Variables defined in yml cannot be overridden at queue time instead overrideable variables must be defined in the web gui. # Commenting out until AzDO supports something like the runtime parameters outlined here: https://github.com/Microsoft/azure-pipelines-yaml/pull/129 #variables: # SignType: test # IbcDrop: 'default' parameters: - name: PRNumber type: number - name: CommitSHA type: string # The variables `_DotNetArtifactsCategory` and `_DotNetValidationArtifactsCategory` are required for proper publishing of build artifacts. See https://github.com/dotnet/roslyn/pull/38259 variables: - name: _DotNetArtifactsCategory value: .NETCore - name: _DotNetValidationArtifactsCategory value: .NETCoreValidation - group: DotNet-Roslyn-SDLValidation-Params # To retrieve OptProf data we need to authenticate to the VS drop storage. # If the pipeline is running in DevDiv, the account has access to the VS drop storage. # Get $AccessToken-dotnet-build-bot-public-repo from DotNet-GitHub-Versions-Repo-Write - group: DotNet-GitHub-Versions-Repo-Write - name: _DevDivDropAccessToken value: $(System.AccessToken) stages: - stage: build displayName: Build and Test jobs: - job: PRValidationBuild displayName: PR Validation Build timeoutInMinutes: 360 # Conditionally set build pool so we can share this YAML when building with different pipeline pool: name: VSEngSS-MicroBuild2017 demands: - msbuild - visualstudio - DotNetFramework steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - task: tagBuildOrRelease@0 displayName: Tag PR validation build inputs: type: 'Build' tags: | PRValidationBuild PRNumber:${{ parameters.PRNumber }} CommitSHA:${{ parameters.CommitSHA }} condition: succeeded() - task: PowerShell@2 displayName: Setup branch for insertion validation inputs: filePath: 'eng\setup-pr-validation.ps1' arguments: '-sourceBranchName $(SourceBranchName) -prNumber ${{ parameters.PRNumber }} -commitSHA ${{ parameters.CommitSHA }}' condition: succeeded() - powershell: Write-Host "##vso[task.setvariable variable=VisualStudio.DropName]Products/$(System.TeamProject)/$(Build.Repository.Name)/$(SourceBranchName)/$(Build.BuildNumber)" displayName: Setting VisualStudio.DropName variable - task: NuGetToolInstaller@0 inputs: versionSpec: '4.9.2' # Authenticate with service connections to be able to publish packages to external nuget feeds. - task: NuGetAuthenticate@0 inputs: nuGetServiceConnections: azure-public/vs-impl, azure-public/vssdk # Needed to restore the Microsoft.DevDiv.Optimization.Data.PowerShell package - task: NuGetCommand@2 displayName: Restore internal tools inputs: command: restore feedsToUse: config restoreSolution: 'eng\common\internal\Tools.csproj' nugetConfigPath: 'NuGet.config' restoreDirectory: '$(Build.SourcesDirectory)\.packages' - task: MicroBuildSigningPlugin@2 inputs: signType: $(SignType) zipSources: false condition: and(succeeded(), in(variables['SignType'], 'test', 'real')) - task: PowerShell@2 displayName: Build inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration $(BuildConfiguration) -officialBuildId $(Build.BuildNumber) -officialSkipTests $(SkipTests) -officialSkipApplyOptimizationData $(SkipApplyOptimizationData) -officialSourceBranchName $(SourceBranchName) -officialIbcDrop $(IbcDrop) -officialVisualStudioDropAccessToken $(_DevDivDropAccessToken) /p:RepositoryName=$(Build.Repository.Name) /p:VisualStudioDropName=$(VisualStudio.DropName) /p:DotNetSignType=$(SignType) /p:DotNetPublishToBlobFeed=false /p:PublishToSymbolServer=false /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:DotNetArtifactsCategory=$(_DotNetArtifactsCategory) /p:DotnetPublishUsingPipelines=false /p:IgnoreIbcMergeErrors=true /p:PreReleaseVersionLabel=pr-validation condition: succeeded() # Publish OptProf generated JSON files as a build artifact. This allows for easy inspection from # a build execution. - task: PublishBuildArtifacts@1 displayName: Publish OptProf Data Files inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\OptProf\$(BuildConfiguration)\Data' ArtifactName: 'OptProf Data Files' condition: succeeded() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)' ArtifactName: 'Build Diagnostic Files' publishLocation: Container continueOnError: true condition: succeededOrFailed() - task: PublishBuildArtifacts@1 displayName: Publish Ngen Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)\ngen' ArtifactName: 'NGen Logs' publishLocation: Container continueOnError: true condition: succeeded() - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\$(BuildConfiguration)\*.xml' mergeTestResults: true testRunTitle: 'Unit Tests' condition: and(succeededOrFailed(), ne(variables['SkipTests'], 'true')) # Publishes setup VSIXes to a drop. # Note: The insertion tool looks for the display name of this task in the logs. - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 displayName: Upload VSTS Drop inputs: DropName: $(VisualStudio.DropName) DropFolder: 'artifacts\VSSetup\$(BuildConfiguration)\Insertion' AccessToken: $(_DevDivDropAccessToken) condition: succeeded() # Publish insertion packages to CoreXT store. - task: NuGetCommand@2 displayName: Publish CoreXT Packages inputs: command: push packagesToPush: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\DevDivPackages\**\*.nupkg' allowPackageConflicts: true feedsToUse: config publishVstsFeed: '97a41293-2972-4f48-8c0e-05493ae82010' condition: succeeded() # Publish an artifact that the RoslynInsertionTool is able to find by its name. - task: PublishBuildArtifacts@1 displayName: Publish Artifact VSSetup inputs: PathtoPublish: 'artifacts\VSSetup\$(BuildConfiguration)' ArtifactName: 'VSSetup' condition: succeeded() - task: ms-vseng.MicroBuildTasks.521a94ea-9e68-468a-8167-6dcf361ea776.MicroBuildCleanup@1 displayName: Perform Cleanup Tasks condition: succeededOrFailed()
resources: - repo: self clean: true # Variables defined in yml cannot be overridden at queue time instead overrideable variables must be defined in the web gui. # Commenting out until AzDO supports something like the runtime parameters outlined here: https://github.com/Microsoft/azure-pipelines-yaml/pull/129 #variables: # SignType: test # IbcDrop: 'default' parameters: - name: PRNumber type: number - name: CommitSHA type: string # The variables `_DotNetArtifactsCategory` and `_DotNetValidationArtifactsCategory` are required for proper publishing of build artifacts. See https://github.com/dotnet/roslyn/pull/38259 variables: - name: _DotNetArtifactsCategory value: .NETCore - name: _DotNetValidationArtifactsCategory value: .NETCoreValidation - group: DotNet-Roslyn-SDLValidation-Params # To retrieve OptProf data we need to authenticate to the VS drop storage. # If the pipeline is running in DevDiv, the account has access to the VS drop storage. # Get $AccessToken-dotnet-build-bot-public-repo from DotNet-GitHub-Versions-Repo-Write - group: DotNet-GitHub-Versions-Repo-Write - name: _DevDivDropAccessToken value: $(System.AccessToken) stages: - stage: build displayName: Build and Test jobs: - job: PRValidationBuild displayName: PR Validation Build timeoutInMinutes: 360 # Conditionally set build pool so we can share this YAML when building with different pipeline pool: name: VSEngSS-MicroBuild2017 demands: - msbuild - visualstudio - DotNetFramework steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - task: tagBuildOrRelease@0 displayName: Tag PR validation build inputs: type: 'Build' tags: | PRValidationBuild PRNumber:${{ parameters.PRNumber }} CommitSHA:${{ parameters.CommitSHA }} condition: succeeded() - task: PowerShell@2 displayName: Setup branch for insertion validation inputs: filePath: 'eng\setup-pr-validation.ps1' arguments: '-sourceBranchName $(SourceBranchName) -prNumber ${{ parameters.PRNumber }} -commitSHA ${{ parameters.CommitSHA }}' condition: succeeded() - powershell: Write-Host "##vso[task.setvariable variable=VisualStudio.DropName]Products/$(System.TeamProject)/$(Build.Repository.Name)/$(SourceBranchName)/$(Build.BuildNumber)" displayName: Setting VisualStudio.DropName variable - task: NuGetToolInstaller@0 inputs: versionSpec: '4.9.2' # Authenticate with service connections to be able to publish packages to external nuget feeds. - task: NuGetAuthenticate@0 inputs: nuGetServiceConnections: azure-public/vs-impl, azure-public/vssdk # Needed to restore the Microsoft.DevDiv.Optimization.Data.PowerShell package - task: NuGetCommand@2 displayName: Restore internal tools inputs: command: restore feedsToUse: config restoreSolution: 'eng\common\internal\Tools.csproj' nugetConfigPath: 'NuGet.config' restoreDirectory: '$(Build.SourcesDirectory)\.packages' - task: MicroBuildSigningPlugin@2 inputs: signType: $(SignType) zipSources: false condition: and(succeeded(), in(variables['SignType'], 'test', 'real')) - task: PowerShell@2 displayName: Build inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration $(BuildConfiguration) -officialBuildId $(Build.BuildNumber) -officialSkipTests $(SkipTests) -officialSkipApplyOptimizationData $(SkipApplyOptimizationData) -officialSourceBranchName $(SourceBranchName) -officialIbcDrop $(IbcDrop) -officialVisualStudioDropAccessToken $(_DevDivDropAccessToken) /p:RepositoryName=$(Build.Repository.Name) /p:VisualStudioDropName=$(VisualStudio.DropName) /p:DotNetSignType=$(SignType) /p:DotNetPublishToBlobFeed=false /p:PublishToSymbolServer=false /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:DotNetArtifactsCategory=$(_DotNetArtifactsCategory) /p:DotnetPublishUsingPipelines=false /p:IgnoreIbcMergeErrors=true /p:PreReleaseVersionLabel=pr-validation /p:IgnoreIbcMergeErrors=true condition: succeeded() # Publish OptProf generated JSON files as a build artifact. This allows for easy inspection from # a build execution. - task: PublishBuildArtifacts@1 displayName: Publish OptProf Data Files inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\OptProf\$(BuildConfiguration)\Data' ArtifactName: 'OptProf Data Files' condition: succeeded() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)' ArtifactName: 'Build Diagnostic Files' publishLocation: Container continueOnError: true condition: succeededOrFailed() - task: PublishBuildArtifacts@1 displayName: Publish Ngen Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)\ngen' ArtifactName: 'NGen Logs' publishLocation: Container continueOnError: true condition: succeeded() - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\$(BuildConfiguration)\*.xml' mergeTestResults: true testRunTitle: 'Unit Tests' condition: and(succeededOrFailed(), ne(variables['SkipTests'], 'true')) # Publishes setup VSIXes to a drop. # Note: The insertion tool looks for the display name of this task in the logs. - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 displayName: Upload VSTS Drop inputs: DropName: $(VisualStudio.DropName) DropFolder: 'artifacts\VSSetup\$(BuildConfiguration)\Insertion' AccessToken: $(_DevDivDropAccessToken) condition: succeeded() # Publish insertion packages to CoreXT store. - task: NuGetCommand@2 displayName: Publish CoreXT Packages inputs: command: push packagesToPush: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\DevDivPackages\**\*.nupkg' allowPackageConflicts: true feedsToUse: config publishVstsFeed: '97a41293-2972-4f48-8c0e-05493ae82010' condition: succeeded() # Publish an artifact that the RoslynInsertionTool is able to find by its name. - task: PublishBuildArtifacts@1 displayName: Publish Artifact VSSetup inputs: PathtoPublish: 'artifacts\VSSetup\$(BuildConfiguration)' ArtifactName: 'VSSetup' condition: succeeded() - task: ms-vseng.MicroBuildTasks.521a94ea-9e68-468a-8167-6dcf361ea776.MicroBuildCleanup@1 displayName: Perform Cleanup Tasks condition: succeededOrFailed()
1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/Tools.props
<Project> <ItemGroup> <!-- This package would normally be restored by the Arcade SDK, but it is not included during restore operations if the -package flag is not also provided during the build. Roslyn separates the restore operation from the build and packaging operations in our build. See https://github.com/dotnet/arcade/issues/7205 --> <PackageReference Include="Microsoft.DotNet.Build.Tasks.Feed" Version="$(MicrosoftDotNetBuildTasksFeedVersion)" /> </ItemGroup> </Project>
<Project> <ItemGroup> <!-- This package would normally be restored by the Arcade SDK, but it is not included during restore operations if the -package flag is not also provided during the build. Roslyn separates the restore operation from the build and packaging operations in our build. See https://github.com/dotnet/arcade/issues/7205 --> <PackageReference Include="Microsoft.DotNet.Build.Tasks.Feed" Version="$(MicrosoftDotNetBuildTasksFeedVersion)" /> <PackageReference Include="Microsoft.DotNet.NuGetRepack.Tasks" Version="$(MicrosoftDotNetBuildTasksFeedVersion)" /> </ItemGroup> </Project>
1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/Versions.props
<?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> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>4</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-3.21373.8</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <CodeStyleAnalyzerVersion>3.10.0</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.2062-g973d339867</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31318-291</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.41</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftDotNetBuildTasksFeedVersion>6.0.0-beta.21319.2</MicrosoftDotNetBuildTasksFeedVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2018</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2018</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21262.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21262.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerClientVersion>17.0.20-g6553c6c46e</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.15-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.15-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.11-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21363.2</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </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> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>4</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-3.21373.8</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <CodeStyleAnalyzerVersion>3.10.0</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.2062-g973d339867</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31318-291</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.41</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2018</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2018</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21262.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21262.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerClientVersion>17.0.20-g6553c6c46e</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.15-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.15-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.11-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21363.2</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </Project>
1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/common/templates/job/onelocbuild.yml
parameters: # Optional: dependencies of the job dependsOn: '' # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: vmImage: vs2017-win2016 CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) SourcesDirectory: $(Build.SourcesDirectory) CreatePr: true AutoCompletePr: false UseLfLineEndings: true UseCheckedInLocProjectJson: false LanguageSet: VS_Main_Languages LclSource: lclFilesInRepo LclPackageId: '' RepoType: gitHub GitHubOrg: dotnet MirrorRepo: '' MirrorBranch: main condition: '' jobs: - job: OneLocBuild dependsOn: ${{ parameters.dependsOn }} displayName: OneLocBuild pool: ${{ parameters.pool }} variables: - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - name: _GenerateLocProjectArguments value: -SourcesDirectory ${{ parameters.SourcesDirectory }} -LanguageSet "${{ parameters.LanguageSet }}" -CreateNeutralXlfs - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - name: _GenerateLocProjectArguments value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson steps: - task: Powershell@2 inputs: filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 arguments: $(_GenerateLocProjectArguments) displayName: Generate LocProject.json condition: ${{ parameters.condition }} - task: OneLocBuild@2 displayName: OneLocBuild env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: locProj: eng/Localize/LocProject.json outDir: $(Build.ArtifactStagingDirectory) lclSource: ${{ parameters.LclSource }} lclPackageId: ${{ parameters.LclPackageId }} isCreatePrSelected: ${{ parameters.CreatePr }} ${{ if eq(parameters.CreatePr, true) }}: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: repoType: ${{ parameters.RepoType }} gitHubPatVariable: "${{ parameters.GithubPat }}" ${{ if ne(parameters.MirrorRepo, '') }}: isMirrorRepoSelected: true gitHubOrganization: ${{ parameters.GitHubOrg }} mirrorRepo: ${{ parameters.MirrorRepo }} mirrorBranch: ${{ parameters.MirrorBranch }} condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish Localization Files inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish LocProject.json inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }}
parameters: # Optional: dependencies of the job dependsOn: '' # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: vmImage: vs2017-win2016 CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) SourcesDirectory: $(Build.SourcesDirectory) CreatePr: true AutoCompletePr: false UseLfLineEndings: true UseCheckedInLocProjectJson: false LanguageSet: VS_Main_Languages LclSource: lclFilesInRepo LclPackageId: '' RepoType: gitHub GitHubOrg: dotnet MirrorRepo: '' MirrorBranch: main condition: '' jobs: - job: OneLocBuild dependsOn: ${{ parameters.dependsOn }} displayName: OneLocBuild pool: ${{ parameters.pool }} variables: - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - name: _GenerateLocProjectArguments value: -SourcesDirectory ${{ parameters.SourcesDirectory }} -LanguageSet "${{ parameters.LanguageSet }}" -CreateNeutralXlfs - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - name: _GenerateLocProjectArguments value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson steps: - task: Powershell@2 inputs: filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 arguments: $(_GenerateLocProjectArguments) displayName: Generate LocProject.json condition: ${{ parameters.condition }} - task: OneLocBuild@2 displayName: OneLocBuild env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: locProj: eng/Localize/LocProject.json outDir: $(Build.ArtifactStagingDirectory) lclSource: ${{ parameters.LclSource }} lclPackageId: ${{ parameters.LclPackageId }} isCreatePrSelected: ${{ parameters.CreatePr }} ${{ if eq(parameters.CreatePr, true) }}: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: repoType: ${{ parameters.RepoType }} gitHubPatVariable: "${{ parameters.GithubPat }}" ${{ if ne(parameters.MirrorRepo, '') }}: isMirrorRepoSelected: true gitHubOrganization: ${{ parameters.GitHubOrg }} mirrorRepo: ${{ parameters.MirrorRepo }} mirrorBranch: ${{ parameters.MirrorBranch }} condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish Localization Files inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish LocProject.json inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/common/templates/steps/run-script-ifequalelse.yml
parameters: # if parameter1 equals parameter 2, run 'ifScript' command, else run 'elsescript' command parameter1: '' parameter2: '' ifScript: '' elseScript: '' # name of script step name: Script # display name of script step displayName: If-Equal-Else Script # environment env: {} # conditional expression for step execution condition: '' steps: - ${{ if and(ne(parameters.ifScript, ''), eq(parameters.parameter1, parameters.parameter2)) }}: - script: ${{ parameters.ifScript }} name: ${{ parameters.name }} displayName: ${{ parameters.displayName }} env: ${{ parameters.env }} condition: ${{ parameters.condition }} - ${{ if and(ne(parameters.elseScript, ''), ne(parameters.parameter1, parameters.parameter2)) }}: - script: ${{ parameters.elseScript }} name: ${{ parameters.name }} displayName: ${{ parameters.displayName }} env: ${{ parameters.env }} condition: ${{ parameters.condition }}
parameters: # if parameter1 equals parameter 2, run 'ifScript' command, else run 'elsescript' command parameter1: '' parameter2: '' ifScript: '' elseScript: '' # name of script step name: Script # display name of script step displayName: If-Equal-Else Script # environment env: {} # conditional expression for step execution condition: '' steps: - ${{ if and(ne(parameters.ifScript, ''), eq(parameters.parameter1, parameters.parameter2)) }}: - script: ${{ parameters.ifScript }} name: ${{ parameters.name }} displayName: ${{ parameters.displayName }} env: ${{ parameters.env }} condition: ${{ parameters.condition }} - ${{ if and(ne(parameters.elseScript, ''), ne(parameters.parameter1, parameters.parameter2)) }}: - script: ${{ parameters.elseScript }} name: ${{ parameters.name }} displayName: ${{ parameters.displayName }} env: ${{ parameters.env }} condition: ${{ parameters.condition }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/pipelines/test-unix-job.yml
# Test on Unix using Helix parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: # Note that when helix is enabled, the agent running this job is essentially # a thin client that kicks off a helix job and waits for it to complete. # Thus we don't use a helix queue to run the job here, and instead use the plentiful AzDO vmImages. vmImage: ubuntu-20.04 timeoutInMinutes: 90 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: ShellScript@2 displayName: Rehydrate RunTests inputs: scriptPath: ./artifacts/bin/RunTests/${{ parameters.configuration }}/netcoreapp3.1/rehydrate.sh env: HELIX_CORRELATION_PAYLOAD: '$(Build.SourcesDirectory)/.duplicate' - task: ShellScript@2 inputs: scriptPath: ./eng/build.sh args: --ci --helix --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} displayName: Test env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
# Test on Unix using Helix parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: # Note that when helix is enabled, the agent running this job is essentially # a thin client that kicks off a helix job and waits for it to complete. # Thus we don't use a helix queue to run the job here, and instead use the plentiful AzDO vmImages. vmImage: ubuntu-20.04 timeoutInMinutes: 90 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: ShellScript@2 displayName: Rehydrate RunTests inputs: scriptPath: ./artifacts/bin/RunTests/${{ parameters.configuration }}/netcoreapp3.1/rehydrate.sh env: HELIX_CORRELATION_PAYLOAD: '$(Build.SourcesDirectory)/.duplicate' - task: ShellScript@2 inputs: scriptPath: ./eng/build.sh args: --ci --helix --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} displayName: Test env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./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,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/common/templates/steps/build-reason.yml
# build-reason.yml # Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons # to include steps (',' separated). parameters: conditions: '' steps: [] steps: - ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}: - ${{ parameters.steps }} - ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}: - ${{ parameters.steps }}
# build-reason.yml # Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons # to include steps (',' separated). parameters: conditions: '' steps: [] steps: - ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}: - ${{ parameters.steps }} - ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}: - ${{ parameters.steps }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Tools/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/pipelines/publish-logs.yml
# Build on windows desktop parameters: - name: jobName type: string default: '' - name: configuration type: string default: 'Debug' steps: - task: PublishPipelineArtifact@1 displayName: Publish Logs inputs: targetPath: '$(Build.SourcesDirectory)/artifacts/log/${{ parameters.configuration }}' artifactName: '${{ parameters.jobName }} Attempt $(System.JobAttempt) Logs' continueOnError: true condition: not(succeeded())
# Build on windows desktop parameters: - name: jobName type: string default: '' - name: configuration type: string default: 'Debug' steps: - task: PublishPipelineArtifact@1 displayName: Publish Logs inputs: targetPath: '$(Build.SourcesDirectory)/artifacts/log/${{ parameters.configuration }}' artifactName: '${{ parameters.jobName }} Attempt $(System.JobAttempt) Logs' continueOnError: true condition: not(succeeded())
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/MSBuildTest/Resources/NetCoreMultiTFM_ExtensionWithConditionOnTFM/Project.csproj.test.props
<Project> <PropertyGroup> <RootNamespace Condition="'$(TargetFramework)' == 'netcoreapp2.1'">Project.NetCore</RootNamespace> <RootNamespace Condition="'$(TargetFramework)' == 'netstandard2.0'">Project.NetStandard</RootNamespace> <RootNamespace Condition="'$(TargetFramework)' == 'net461'">Project.NetFramework</RootNamespace> </PropertyGroup> </Project>
<Project> <PropertyGroup> <RootNamespace Condition="'$(TargetFramework)' == 'netcoreapp2.1'">Project.NetCore</RootNamespace> <RootNamespace Condition="'$(TargetFramework)' == 'netstandard2.0'">Project.NetStandard</RootNamespace> <RootNamespace Condition="'$(TargetFramework)' == 'net461'">Project.NetFramework</RootNamespace> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/NuGet/Microsoft.Net.Compilers.Toolset/build/Microsoft.Net.Compilers.Toolset.props
<!-- Licensed to the .NET Foundation under one or more 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> <PropertyGroup> <_RoslynTargetDirectoryName Condition="'$(MSBuildRuntimeType)' == 'Core'">netcoreapp3.1</_RoslynTargetDirectoryName> <_RoslynTargetDirectoryName Condition="'$(MSBuildRuntimeType)' != 'Core'">net472</_RoslynTargetDirectoryName> <_RoslynTasksDirectory>$(MSBuildThisFileDirectory)..\tasks\$(_RoslynTargetDirectoryName)\</_RoslynTasksDirectory> <RoslynTasksAssembly>$(_RoslynTasksDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll</RoslynTasksAssembly> <UseSharedCompilation Condition="'$(UseSharedCompilation)' == ''">true</UseSharedCompilation> <CSharpCoreTargetsPath>$(_RoslynTasksDirectory)Microsoft.CSharp.Core.targets</CSharpCoreTargetsPath> <VisualBasicCoreTargetsPath>$(_RoslynTasksDirectory)Microsoft.VisualBasic.Core.targets</VisualBasicCoreTargetsPath> </PropertyGroup> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc" AssemblyFile="$(RoslynTasksAssembly)" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc" AssemblyFile="$(RoslynTasksAssembly)" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.CopyRefAssembly" AssemblyFile="$(RoslynTasksAssembly)" /> </Project>
<!-- Licensed to the .NET Foundation under one or more 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> <PropertyGroup> <_RoslynTargetDirectoryName Condition="'$(MSBuildRuntimeType)' == 'Core'">netcoreapp3.1</_RoslynTargetDirectoryName> <_RoslynTargetDirectoryName Condition="'$(MSBuildRuntimeType)' != 'Core'">net472</_RoslynTargetDirectoryName> <_RoslynTasksDirectory>$(MSBuildThisFileDirectory)..\tasks\$(_RoslynTargetDirectoryName)\</_RoslynTasksDirectory> <RoslynTasksAssembly>$(_RoslynTasksDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll</RoslynTasksAssembly> <UseSharedCompilation Condition="'$(UseSharedCompilation)' == ''">true</UseSharedCompilation> <CSharpCoreTargetsPath>$(_RoslynTasksDirectory)Microsoft.CSharp.Core.targets</CSharpCoreTargetsPath> <VisualBasicCoreTargetsPath>$(_RoslynTasksDirectory)Microsoft.VisualBasic.Core.targets</VisualBasicCoreTargetsPath> </PropertyGroup> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc" AssemblyFile="$(RoslynTasksAssembly)" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc" AssemblyFile="$(RoslynTasksAssembly)" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.CopyRefAssembly" AssemblyFile="$(RoslynTasksAssembly)" /> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/Publishing.props
<?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <PublishingVersion>3</PublishingVersion> </PropertyGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <PublishingVersion>3</PublishingVersion> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/pipelines/checkout-unix-task.yml
# Shallow checkout sources on Unix steps: - checkout: none - script: | set -x git init git remote add origin "$(Build.Repository.Uri)" git fetch --progress --no-tags --depth=1 origin "$(Build.SourceVersion)" git checkout "$(Build.SourceVersion)" displayName: Shallow Checkout
# Shallow checkout sources on Unix steps: - checkout: none - script: | set -x git init git remote add origin "$(Build.Repository.Uri)" git fetch --progress --no-tags --depth=1 origin "$(Build.SourceVersion)" git checkout "$(Build.SourceVersion)" displayName: Shallow Checkout
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/common/templates/phases/base.yml
parameters: # Optional: Clean sources before building clean: true # Optional: Git fetch depth fetchDepth: '' # Optional: name of the phase (not specifying phase name may cause name collisions) name: '' # Optional: display name of the phase displayName: '' # Optional: condition for the job to run condition: '' # Optional: dependencies of the phase dependsOn: '' # Required: A defined YAML queue queue: {} # Required: build steps steps: [] # Optional: variables variables: {} # Optional: should run as a public build even in the internal project # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false ## Telemetry variables # Optional: enable sending telemetry # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix # _HelixBuildConfig - differentiate between Debug, Release, other # _HelixSource - Example: build/product # _HelixType - Example: official/dotnet/arcade/$(Build.SourceBranch) enableTelemetry: false # Optional: Enable installing Microbuild plugin # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix # _TeamName - the name of your team # _SignType - 'test' or 'real' enableMicrobuild: false # 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. phases: - phase: ${{ parameters.name }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} queue: ${{ parameters.queue }} ${{ if ne(parameters.variables, '') }}: variables: ${{ insert }}: ${{ parameters.variables }} steps: - checkout: self clean: ${{ parameters.clean }} ${{ if ne(parameters.fetchDepth, '') }}: fetchDepth: ${{ parameters.fetchDepth }} - ${{ if eq(parameters.enableTelemetry, 'true') }}: - template: /eng/common/templates/steps/telemetry-start.yml parameters: buildConfig: $(_HelixBuildConfig) helixSource: $(_HelixSource) helixType: $(_HelixType) runAsPublic: ${{ parameters.runAsPublic }} - ${{ if eq(parameters.enableMicrobuild, 'true') }}: # Internal only resource, and Microbuild signing shouldn't be applied to PRs. - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - 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: false condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) # Run provided build steps - ${{ parameters.steps }} - ${{ if eq(parameters.enableMicrobuild, 'true') }}: # Internal only resources - ${{ 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')) env: TeamName: $(_TeamName) - ${{ if eq(parameters.enableTelemetry, 'true') }}: - template: /eng/common/templates/steps/telemetry-end.yml parameters: helixSource: $(_HelixSource) helixType: $(_HelixType) - ${{ if and(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: false condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: false condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
parameters: # Optional: Clean sources before building clean: true # Optional: Git fetch depth fetchDepth: '' # Optional: name of the phase (not specifying phase name may cause name collisions) name: '' # Optional: display name of the phase displayName: '' # Optional: condition for the job to run condition: '' # Optional: dependencies of the phase dependsOn: '' # Required: A defined YAML queue queue: {} # Required: build steps steps: [] # Optional: variables variables: {} # Optional: should run as a public build even in the internal project # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false ## Telemetry variables # Optional: enable sending telemetry # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix # _HelixBuildConfig - differentiate between Debug, Release, other # _HelixSource - Example: build/product # _HelixType - Example: official/dotnet/arcade/$(Build.SourceBranch) enableTelemetry: false # Optional: Enable installing Microbuild plugin # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix # _TeamName - the name of your team # _SignType - 'test' or 'real' enableMicrobuild: false # 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. phases: - phase: ${{ parameters.name }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} queue: ${{ parameters.queue }} ${{ if ne(parameters.variables, '') }}: variables: ${{ insert }}: ${{ parameters.variables }} steps: - checkout: self clean: ${{ parameters.clean }} ${{ if ne(parameters.fetchDepth, '') }}: fetchDepth: ${{ parameters.fetchDepth }} - ${{ if eq(parameters.enableTelemetry, 'true') }}: - template: /eng/common/templates/steps/telemetry-start.yml parameters: buildConfig: $(_HelixBuildConfig) helixSource: $(_HelixSource) helixType: $(_HelixType) runAsPublic: ${{ parameters.runAsPublic }} - ${{ if eq(parameters.enableMicrobuild, 'true') }}: # Internal only resource, and Microbuild signing shouldn't be applied to PRs. - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - 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: false condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) # Run provided build steps - ${{ parameters.steps }} - ${{ if eq(parameters.enableMicrobuild, 'true') }}: # Internal only resources - ${{ 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')) env: TeamName: $(_TeamName) - ${{ if eq(parameters.enableTelemetry, 'true') }}: - template: /eng/common/templates/steps/telemetry-end.yml parameters: helixSource: $(_HelixSource) helixType: $(_HelixType) - ${{ if and(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: false condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: false condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Setup/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/common/templates/job/execute-sdl.yml
parameters: enable: 'false' # Whether the SDL validation job should execute or not overrideParameters: '' # Optional: to override values for parameters. additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' # Optional: if specified, restore and use this version of Guardian instead of the default. overrideGuardianVersion: '' # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth # diagnosis of problems with specific tool configurations. publishGuardianDirectoryToPipeline: false # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL # parameters rather than relying on YAML. It may be better to use a local script, because you can # reproduce results locally without piecing together a command based on the YAML. executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named # 'continueOnError', the parameter value is not correctly picked up. # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter sdlContinueOnError: false # optional: determines whether to continue the build if the step errors; # optional: determines if build artifacts should be downloaded. downloadArtifacts: true # optional: determines if this job should search the directory of downloaded artifacts for # 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks. extractArchiveArtifacts: false dependsOn: '' # Optional: dependencies of the job artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts # Usage: # artifactNames: # - 'BlobArtifacts' # - 'Artifacts_Windows_NT_Release' # Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts, # not pipeline artifacts, so doesn't affect the use of this parameter. pipelineArtifactNames: [] # Optional: location and ID of the AzDO build that the build/pipeline artifacts should be # downloaded from. By default, uses runtime expressions to decide based on the variables set by # the 'setupMaestroVars' dependency. Overriding this parameter is necessary if SDL tasks are # running without Maestro++/BAR involved, or to download artifacts from a specific existing build # to iterate quickly on SDL changes. AzDOProjectName: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] AzDOPipelineId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] AzDOBuildId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] jobs: - job: Run_SDL dependsOn: ${{ parameters.dependsOn }} displayName: Run SDL tool condition: eq( ${{ parameters.enable }}, 'true') variables: - group: DotNet-VSTS-Bot - name: AzDOProjectName value: ${{ parameters.AzDOProjectName }} - name: AzDOPipelineId value: ${{ parameters.AzDOPipelineId }} - name: AzDOBuildId value: ${{ parameters.AzDOBuildId }} # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in # sync with the packages.config file. - name: DefaultGuardianVersion value: 0.53.3 - name: GuardianVersion value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} - name: GuardianPackagesConfigFile value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config pool: # To extract archives (.tar.gz, .zip), we need access to "tar", added in Windows 10/2019. ${{ if eq(parameters.extractArchiveArtifacts, 'false') }}: name: Hosted VS2017 ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: vmImage: windows-2019 steps: - checkout: self clean: true - ${{ if ne(parameters.downloadArtifacts, 'false')}}: - ${{ if ne(parameters.artifactNames, '') }}: - ${{ each artifactName in parameters.artifactNames }}: - task: DownloadBuildArtifacts@0 displayName: Download Build Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) artifactName: ${{ artifactName }} downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - ${{ if eq(parameters.artifactNames, '') }}: - task: DownloadBuildArtifacts@0 displayName: Download Build Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: specific files itemPattern: "**" downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - ${{ each artifactName in parameters.pipelineArtifactNames }}: - task: DownloadPipelineArtifact@2 displayName: Download Pipeline Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) artifactName: ${{ artifactName }} downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts displayName: Extract Blob Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts displayName: Extract Package Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: - powershell: eng/common/sdl/extract-artifact-archives.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts displayName: Extract Archive Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.overrideGuardianVersion, '') }}: - powershell: | $content = Get-Content $(GuardianPackagesConfigFile) Write-Host "packages.config content was:`n$content" $content = $content.Replace('$(DefaultGuardianVersion)', '$(GuardianVersion)') $content | Set-Content $(GuardianPackagesConfigFile) Write-Host "packages.config content updated to:`n$content" displayName: Use overridden Guardian version ${{ parameters.overrideGuardianVersion }} - task: NuGetToolInstaller@1 displayName: 'Install NuGet.exe' - task: NuGetCommand@2 displayName: 'Install Guardian' inputs: restoreSolution: $(Build.SourcesDirectory)\eng\common\sdl\packages.config feedsToUse: config nugetConfigPath: $(Build.SourcesDirectory)\eng\common\sdl\NuGet.config externalFeedCredentials: GuardianConnect restoreDirectory: $(Build.SourcesDirectory)\.packages - ${{ if ne(parameters.overrideParameters, '') }}: - powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if eq(parameters.overrideParameters, '') }}: - powershell: ${{ parameters.executeAllSdlToolsScript }} -GuardianPackageName Microsoft.Guardian.Cli.$(GuardianVersion) -NugetPackageDirectory $(Build.SourcesDirectory)\.packages -AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw) ${{ parameters.additionalParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}: # We want to publish the Guardian results and configuration for easy diagnosis. However, the # '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default # tooling files. Some of these files are large and aren't useful during an investigation, so # exclude them by simply deleting them before publishing. (As of writing, there is no documented # way to selectively exclude a dir from the pipeline artifact publish task.) - task: DeleteFiles@1 displayName: Delete Guardian dependencies to avoid uploading inputs: SourceFolder: $(Agent.BuildDirectory)/.gdn Contents: | c i condition: succeededOrFailed() - publish: $(Agent.BuildDirectory)/.gdn artifact: GuardianConfiguration displayName: Publish GuardianConfiguration condition: succeededOrFailed()
parameters: enable: 'false' # Whether the SDL validation job should execute or not overrideParameters: '' # Optional: to override values for parameters. additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' # Optional: if specified, restore and use this version of Guardian instead of the default. overrideGuardianVersion: '' # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth # diagnosis of problems with specific tool configurations. publishGuardianDirectoryToPipeline: false # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL # parameters rather than relying on YAML. It may be better to use a local script, because you can # reproduce results locally without piecing together a command based on the YAML. executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named # 'continueOnError', the parameter value is not correctly picked up. # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter sdlContinueOnError: false # optional: determines whether to continue the build if the step errors; # optional: determines if build artifacts should be downloaded. downloadArtifacts: true # optional: determines if this job should search the directory of downloaded artifacts for # 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks. extractArchiveArtifacts: false dependsOn: '' # Optional: dependencies of the job artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts # Usage: # artifactNames: # - 'BlobArtifacts' # - 'Artifacts_Windows_NT_Release' # Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts, # not pipeline artifacts, so doesn't affect the use of this parameter. pipelineArtifactNames: [] # Optional: location and ID of the AzDO build that the build/pipeline artifacts should be # downloaded from. By default, uses runtime expressions to decide based on the variables set by # the 'setupMaestroVars' dependency. Overriding this parameter is necessary if SDL tasks are # running without Maestro++/BAR involved, or to download artifacts from a specific existing build # to iterate quickly on SDL changes. AzDOProjectName: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] AzDOPipelineId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] AzDOBuildId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] jobs: - job: Run_SDL dependsOn: ${{ parameters.dependsOn }} displayName: Run SDL tool condition: eq( ${{ parameters.enable }}, 'true') variables: - group: DotNet-VSTS-Bot - name: AzDOProjectName value: ${{ parameters.AzDOProjectName }} - name: AzDOPipelineId value: ${{ parameters.AzDOPipelineId }} - name: AzDOBuildId value: ${{ parameters.AzDOBuildId }} # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in # sync with the packages.config file. - name: DefaultGuardianVersion value: 0.53.3 - name: GuardianVersion value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} - name: GuardianPackagesConfigFile value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config pool: # To extract archives (.tar.gz, .zip), we need access to "tar", added in Windows 10/2019. ${{ if eq(parameters.extractArchiveArtifacts, 'false') }}: name: Hosted VS2017 ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: vmImage: windows-2019 steps: - checkout: self clean: true - ${{ if ne(parameters.downloadArtifacts, 'false')}}: - ${{ if ne(parameters.artifactNames, '') }}: - ${{ each artifactName in parameters.artifactNames }}: - task: DownloadBuildArtifacts@0 displayName: Download Build Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) artifactName: ${{ artifactName }} downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - ${{ if eq(parameters.artifactNames, '') }}: - task: DownloadBuildArtifacts@0 displayName: Download Build Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: specific files itemPattern: "**" downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - ${{ each artifactName in parameters.pipelineArtifactNames }}: - task: DownloadPipelineArtifact@2 displayName: Download Pipeline Artifacts inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) artifactName: ${{ artifactName }} downloadPath: $(Build.ArtifactStagingDirectory)\artifacts checkDownloadedFiles: true - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts displayName: Extract Blob Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - powershell: eng/common/sdl/extract-artifact-packages.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts displayName: Extract Package Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: - powershell: eng/common/sdl/extract-artifact-archives.ps1 -InputPath $(Build.ArtifactStagingDirectory)\artifacts -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts displayName: Extract Archive Artifacts continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.overrideGuardianVersion, '') }}: - powershell: | $content = Get-Content $(GuardianPackagesConfigFile) Write-Host "packages.config content was:`n$content" $content = $content.Replace('$(DefaultGuardianVersion)', '$(GuardianVersion)') $content | Set-Content $(GuardianPackagesConfigFile) Write-Host "packages.config content updated to:`n$content" displayName: Use overridden Guardian version ${{ parameters.overrideGuardianVersion }} - task: NuGetToolInstaller@1 displayName: 'Install NuGet.exe' - task: NuGetCommand@2 displayName: 'Install Guardian' inputs: restoreSolution: $(Build.SourcesDirectory)\eng\common\sdl\packages.config feedsToUse: config nugetConfigPath: $(Build.SourcesDirectory)\eng\common\sdl\NuGet.config externalFeedCredentials: GuardianConnect restoreDirectory: $(Build.SourcesDirectory)\.packages - ${{ if ne(parameters.overrideParameters, '') }}: - powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if eq(parameters.overrideParameters, '') }}: - powershell: ${{ parameters.executeAllSdlToolsScript }} -GuardianPackageName Microsoft.Guardian.Cli.$(GuardianVersion) -NugetPackageDirectory $(Build.SourcesDirectory)\.packages -AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw) ${{ parameters.additionalParameters }} displayName: Execute SDL continueOnError: ${{ parameters.sdlContinueOnError }} - ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}: # We want to publish the Guardian results and configuration for easy diagnosis. However, the # '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default # tooling files. Some of these files are large and aren't useful during an investigation, so # exclude them by simply deleting them before publishing. (As of writing, there is no documented # way to selectively exclude a dir from the pipeline artifact publish task.) - task: DeleteFiles@1 displayName: Delete Guardian dependencies to avoid uploading inputs: SourceFolder: $(Agent.BuildDirectory)/.gdn Contents: | c i condition: succeededOrFailed() - publish: $(Agent.BuildDirectory)/.gdn artifact: GuardianConfiguration displayName: Publish GuardianConfiguration condition: succeededOrFailed()
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/pipelines/test-unix-job-single-machine.yml
# Test on Unix using a single machine parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' - name: queueName type: string default: '' - name: vmImageName type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: ${{ if ne(parameters.queueName, '') }}: name: NetCorePublic-Pool queue: ${{ parameters.queueName }} ${{ if ne(parameters.vmImageName, '') }}: vmImage: ${{ parameters.vmImageName }} timeoutInMinutes: 40 variables: DOTNET_ROLL_FORWARD: LatestMajor DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: ShellScript@2 displayName: Rehydrate Unit Tests Environment inputs: scriptPath: ./rehydrate-all.sh - task: ShellScript@2 inputs: scriptPath: ./eng/build.sh args: --ci --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} displayName: Test - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)/artifacts/TestResults/${{ parameters.configuration }}/*.xml' mergeTestResults: true testRunTitle: ${{ parameters.testRunName }} condition: always() - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
# Test on Unix using a single machine parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' - name: queueName type: string default: '' - name: vmImageName type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: ${{ if ne(parameters.queueName, '') }}: name: NetCorePublic-Pool queue: ${{ parameters.queueName }} ${{ if ne(parameters.vmImageName, '') }}: vmImage: ${{ parameters.vmImageName }} timeoutInMinutes: 40 variables: DOTNET_ROLL_FORWARD: LatestMajor DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: ShellScript@2 displayName: Rehydrate Unit Tests Environment inputs: scriptPath: ./rehydrate-all.sh - task: ShellScript@2 inputs: scriptPath: ./eng/build.sh args: --ci --configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} displayName: Test - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)/artifacts/TestResults/${{ parameters.configuration }}/*.xml' mergeTestResults: true testRunTitle: ${{ parameters.testRunName }} condition: always() - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/NuGet/Microsoft.NETCore.Compilers/build/Microsoft.NETCore.Compilers.props
<?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="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="ValidateMSBuildToolsVersion" Condition="'$(BuildingProject)' == 'true'"> <!-- The new editorconfig support requires MSBuild version 16.3. --> <Error Text="Microsoft.NETCore.Compilers is only supported on MSBuild v16.3 and above" Condition="'$(MSBuildVersion)' &lt; '16.3'" /> </Target> <!-- Always use the local build task, even if we just shell out to an exe in case there are new properties in the local build task. --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.CopyRefAssembly" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <PropertyGroup> <!-- Don't use the compiler server by default in the NuGet package. --> <UseSharedCompilation Condition="'$(UseSharedCompilation)' == ''">false</UseSharedCompilation> <CSharpCoreTargetsPath>$(MSBuildThisFileDirectory)..\tools\Microsoft.CSharp.Core.targets</CSharpCoreTargetsPath> <VisualBasicCoreTargetsPath>$(MSBuildThisFileDirectory)..\tools\Microsoft.VisualBasic.Core.targets</VisualBasicCoreTargetsPath> </PropertyGroup> <!-- Older versions of the CLI didn't set the DOTNET_HOST_PATH variable, which means we have to use our shell wrappers and hope 'dotnet' is on the path. --> <PropertyGroup Condition="'$(DOTNET_HOST_PATH)' == ''"> <CscToolPath>$(MSBuildThisFileDirectory)..\tools\bincore</CscToolPath> <CscToolExe Condition="'$(OS)' == 'Windows_NT'">RunCsc.cmd</CscToolExe> <CscToolExe Condition="'$(OS)' != 'Windows_NT'">RunCsc</CscToolExe> <VbcToolPath>$(MSBuildThisFileDirectory)..\tools\bincore</VbcToolPath> <VbcToolExe Condition="'$(OS)' == 'Windows_NT'">RunVbc.cmd</VbcToolExe> <VbcToolExe Condition="'$(OS)' != 'Windows_NT'">RunVbc</VbcToolExe> </PropertyGroup> <!-- If packaged on Windows, the RunCsc and RunVbc scripts may not be marked executable. If we're not running on Windows, mark them as such, just in case --> <Target Name="MakeCompilerScriptsExecutable" Condition="'$(BuildingProject)' == 'true' AND '$(OS)' != 'Windows_NT' AND ('$(CscToolPath)' != '' OR '$(VbcToolPath)' != '')" BeforeTargets="CoreCompile"> <Exec Command="chmod +x &quot;$(CscToolPath)/$(CscToolExe)&quot; &quot;$(VbcToolPath)/$(VbcToolExe)&quot;" /> </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="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="ValidateMSBuildToolsVersion" Condition="'$(BuildingProject)' == 'true'"> <!-- The new editorconfig support requires MSBuild version 16.3. --> <Error Text="Microsoft.NETCore.Compilers is only supported on MSBuild v16.3 and above" Condition="'$(MSBuildVersion)' &lt; '16.3'" /> </Target> <!-- Always use the local build task, even if we just shell out to an exe in case there are new properties in the local build task. --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.CopyRefAssembly" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\Microsoft.Build.Tasks.CodeAnalysis.dll" /> <PropertyGroup> <!-- Don't use the compiler server by default in the NuGet package. --> <UseSharedCompilation Condition="'$(UseSharedCompilation)' == ''">false</UseSharedCompilation> <CSharpCoreTargetsPath>$(MSBuildThisFileDirectory)..\tools\Microsoft.CSharp.Core.targets</CSharpCoreTargetsPath> <VisualBasicCoreTargetsPath>$(MSBuildThisFileDirectory)..\tools\Microsoft.VisualBasic.Core.targets</VisualBasicCoreTargetsPath> </PropertyGroup> <!-- Older versions of the CLI didn't set the DOTNET_HOST_PATH variable, which means we have to use our shell wrappers and hope 'dotnet' is on the path. --> <PropertyGroup Condition="'$(DOTNET_HOST_PATH)' == ''"> <CscToolPath>$(MSBuildThisFileDirectory)..\tools\bincore</CscToolPath> <CscToolExe Condition="'$(OS)' == 'Windows_NT'">RunCsc.cmd</CscToolExe> <CscToolExe Condition="'$(OS)' != 'Windows_NT'">RunCsc</CscToolExe> <VbcToolPath>$(MSBuildThisFileDirectory)..\tools\bincore</VbcToolPath> <VbcToolExe Condition="'$(OS)' == 'Windows_NT'">RunVbc.cmd</VbcToolExe> <VbcToolExe Condition="'$(OS)' != 'Windows_NT'">RunVbc</VbcToolExe> </PropertyGroup> <!-- If packaged on Windows, the RunCsc and RunVbc scripts may not be marked executable. If we're not running on Windows, mark them as such, just in case --> <Target Name="MakeCompilerScriptsExecutable" Condition="'$(BuildingProject)' == 'true' AND '$(OS)' != 'Windows_NT' AND ('$(CscToolPath)' != '' OR '$(VbcToolPath)' != '')" BeforeTargets="CoreCompile"> <Exec Command="chmod +x &quot;$(CscToolPath)/$(CscToolExe)&quot; &quot;$(VbcToolPath)/$(VbcToolExe)&quot;" /> </Target> </Project>
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./eng/pipelines/test-windows-job.yml
# Test on Windows Desktop using Helix parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: # Note that when helix is enabled, the agent running this job is essentially # a thin client that kicks off a helix job and waits for it to complete. # Thus we don't use a helix queue to run the job here, and instead use the plentiful AzDO vmImages. vmImage: windows-2019 timeoutInMinutes: 120 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: BatchScript@1 displayName: Rehydrate RunTests inputs: filename: ./artifacts/bin/RunTests/${{ parameters.configuration }}/netcoreapp3.1/rehydrate.cmd env: HELIX_CORRELATION_PAYLOAD: '$(Build.SourcesDirectory)\.duplicate' - task: PowerShell@2 displayName: Run Unit Tests inputs: filePath: eng/build.ps1 arguments: -ci -helix -configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} -collectDumps env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
# Test on Windows Desktop using Helix parameters: - name: testRunName type: string default: '' - name: jobName type: string default: '' - name: buildJobName type: string default: '' - name: testArtifactName type: string default: '' - name: configuration type: string default: 'Debug' - name: testArguments type: string default: '' jobs: - job: ${{ parameters.jobName }} dependsOn: ${{ parameters.buildJobName }} pool: # Note that when helix is enabled, the agent running this job is essentially # a thin client that kicks off a helix job and waits for it to complete. # Thus we don't use a helix queue to run the job here, and instead use the plentiful AzDO vmImages. vmImage: windows-2019 timeoutInMinutes: 120 steps: - checkout: none - task: DownloadPipelineArtifact@2 displayName: Download Test Payload inputs: artifact: ${{ parameters.testArtifactName }} path: '$(Build.SourcesDirectory)' - task: BatchScript@1 displayName: Rehydrate RunTests inputs: filename: ./artifacts/bin/RunTests/${{ parameters.configuration }}/netcoreapp3.1/rehydrate.cmd env: HELIX_CORRELATION_PAYLOAD: '$(Build.SourcesDirectory)\.duplicate' - task: PowerShell@2 displayName: Run Unit Tests inputs: filePath: eng/build.ps1 arguments: -ci -helix -configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} -collectDumps env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - template: publish-logs.yml parameters: configuration: ${{ parameters.configuration }} jobName: ${{ parameters.jobName }}
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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 ```
./.github/ISSUE_TEMPLATE/config.yml
blank_issues_enabled: true contact_links: - name: Report issues related to CAxxxx rules url: https://github.com/dotnet/roslyn-analyzers/issues/new/choose about: Enhancements and bug reports to CAxxxx rules are reported to dotnet/roslyn-analyzers repository. - name: Suggest language feature url: https://github.com/dotnet/csharplang/issues/new/choose about: Language feature suggestions are discussed in dotnet/csharplang repository first.
blank_issues_enabled: true contact_links: - name: Report issues related to CAxxxx rules url: https://github.com/dotnet/roslyn-analyzers/issues/new/choose about: Enhancements and bug reports to CAxxxx rules are reported to dotnet/roslyn-analyzers repository. - name: Suggest language feature url: https://github.com/dotnet/csharplang/issues/new/choose about: Language feature suggestions are discussed in dotnet/csharplang repository first.
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/FormattingResult.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.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// this holds onto changes made by formatting engine. /// </summary> internal class FormattingResult : AbstractFormattingResult { internal FormattingResult(TreeData treeInfo, TokenStream tokenStream, TextSpan spanToFormat) : base(treeInfo, tokenStream, spanToFormat) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.TreeInfo.Root, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), this.FormattedSpan), changeMap, cancellationToken); return rewriter.Transform(); } } }
// Licensed to the .NET Foundation under one or more 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.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// this holds onto changes made by formatting engine. /// </summary> internal class FormattingResult : AbstractFormattingResult { internal FormattingResult(TreeData treeInfo, TokenStream tokenStream, TextSpan spanToFormat) : base(treeInfo, tokenStream, spanToFormat) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.TreeInfo.Root, SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), this.FormattedSpan), changeMap, cancellationToken); return rewriter.Transform(); } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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_IUsingStatement.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_IUsingStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_SimpleUsingNewVariable() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c = new C()) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.AsyncStreams)] [Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")] public void IUsingAwaitStatement_SimpleAwaitUsing() { string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { public static async Task M1(IAsyncDisposable disposable) { /*<bind>*/await using (var c = disposable) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (IsAsynchronous) (OperationKind.Using, Type: null) (Syntax: 'await using ... }') Locals: Local_1: System.IAsyncDisposable c Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = disposable') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = disposable') Declarators: IVariableDeclaratorOperation (Symbol: System.IAsyncDisposable c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = disposable') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= disposable') IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable') Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.AsyncStreams)] [Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")] public void UsingFlow_SimpleAwaitUsing() { string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { public static async Task M1(IAsyncDisposable disposable) /*<bind>*/{ await using (var c = disposable) { Console.WriteLine(c.ToString()); } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IAsyncDisposable c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Right: IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = disposable') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = disposable') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsImplicit) (Syntax: 'c = disposable') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_MultipleNewVariable() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (C c1 = new C(), c2 = new C()) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (C c1 ... }') Locals: Local_1: C c1 Local_2: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C c1 = new ... 2 = new C()') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c1 = new ... 2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_SimpleUsingStatementExistingResource() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c = new C(); /*<bind>*/using (c) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c) ... }') Resources: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NestedUsingNewResources() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c1 = new C()) using (var c2 = new C()) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c1 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c2 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NestedUsingExistingResources() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c1 = new C(); var c2 = new C(); /*<bind>*/using (c1) using (c2) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c1) ... }') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Body: IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c2) ... }') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidMultipleVariableDeclaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c1 = new C(), c2 = new C()) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Local_2: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = ne ... 2 = new C()') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = ne ... 2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/using (var c1 = new C(), c2 = new C()) Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C(), c2 = new C()").WithLocation(12, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IOperationTests_MultipleExistingResourcesPassed() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ var c1 = new C(); var c2 = new C(); using (c1, c2) { Console.WriteLine(c1.ToString() + c2.ToString()); } }/*</bind>*/ } "; // Capturing the whole block here, to show that the using statement is actually being bound as a using statement, followed by // an expression and a separate block, rather than being bound as a using statement with an invalid expression as the resources string expectedOperationTree = @" IBlockOperation (5 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') Locals: Local_1: C c1 Local_2: C c2 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c1 = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c2 = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1') Body: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c2') Expression: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c2') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // using (c1, c2) Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(14, 18), // CS1525: Invalid expression term ',' // using (c1, c2) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(14, 18), // CS1002: ; expected // using (c1, c2) Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(14, 18), // CS1513: } expected // using (c1, c2) Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(14, 18), // CS1002: ; expected // using (c1, c2) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(14, 22), // CS1513: } expected // using (c1, c2) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(14, 22) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidNonDisposableNewResource() { string source = @" using System; class C { public static void M1() { /*<bind>*/using (var c1 = new C()) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable' // /*<bind>*/using (var c1 = new C()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var c1 = new C()").WithArguments("C").WithLocation(9, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidNonDisposableExistingResource() { string source = @" using System; class C { public static void M1() { var c1 = new C(); /*<bind>*/using (c1) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1) ... }') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable' // /*<bind>*/using (c1) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1").WithArguments("C").WithLocation(10, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidEmptyUsingResources() { string source = @" using System; class C { public static void M1() { /*<bind>*/using () { }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using () ... }') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // /*<bind>*/using () Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingWithoutSavedReference() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (GetC()) { }/*</bind>*/ } public static C GetC() => new C(); } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (GetC ... }') Resources: IInvocationOperation (C C.GetC()) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DynamicArgument() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { dynamic d = null; /*<bind>*/using (d) { Console.WriteLine(d); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (d) ... }') Resources: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Console.WriteLine(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""WriteLine"", Containing Type: System.Console) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Console.WriteLine') Type Arguments(0) Instance Receiver: null Arguments(1): ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NullResource() { string source = @" using System; class C { public static void M1() { /*<bind>*/using (null) { }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (null ... }') Resources: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_Declaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (/*<bind>*/var c = new C()/*</bind>*/) { Console.WriteLine(c.ToString()); } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_StatementSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (var c = new C()) /*<bind>*/{ Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_ExpressionSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c = new C(); using (/*<bind>*/c/*</bind>*/) { Console.WriteLine(c.ToString()); } } } "; string expectedOperationTree = @" ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_VariableDeclaratorSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (C /*<bind>*/c1 = new C()/*</bind>*/, c2 = new C()) { Console.WriteLine(c1.ToString()); } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_OutVarInResource() { string source = @" class P : System.IDisposable { public void Dispose() { } void M(P p) { /*<bind>*/using (p = M2(out int c)) { c = 1; }/*</bind>*/ } P M2(out int c) { c = 0; return new P(); } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (p = ... }') Locals: Local_1: System.Int32 c Resources: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p') Right: IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DefaultDisposeArguments() { string source = @" class C { public static void M1() { /*<bind>*/using(var s = new S()) { }/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(var s ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(var s ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_ExpressionDefaultDisposeArguments() { string source = @" class C { public static void M1() { var s = new S(); /*<bind>*/using(s) { }/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(s) ... }') Resources: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(s) ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(s) ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(s) ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(s) ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(s) ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParams() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } ref struct S { public void Dispose(params object[] extras = null) { } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()') Instance Receiver: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(19,25): error CS1751: Cannot specify a default value for a parameter array // public void Dispose(params object[] extras = null) { } Diagnostic(ErrorCode.ERR_DefaultValueForParamsParameter, "params").WithLocation(19, 25) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } //THEORY: we won't ever call a params in normal form, because we ignore the default value in metadata. // So: it's either a valid params parameter, in which case we call it in the extended way. // Or its an invalid params parameter, in which case we can't use it, and we error out. // Interestingly we check params before we check default, so a params int = 3 will be callable with an // argument, but not without. [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] object[] extras ) cil managed { .param [1] = nullref .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("C.M2", @" { // Code size 21 (0x15) .maxstack 2 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: call ""object[] System.Array.Empty<object>()"" IL_000f: call ""void S.Dispose(params object[])"" IL_0014: ret } "); verifier.VerifyIL("C.M1", @" { // Code size 24 (0x18) .maxstack 2 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" .try { IL_0008: leave.s IL_0017 } finally { IL_000a: ldloca.s V_0 IL_000c: call ""object[] System.Array.Empty<object>()"" IL_0011: call ""void S.Dispose(params object[])"" IL_0016: endfinally } IL_0017: ret } "); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()') Instance Receiver: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( int32 extras ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayOptionalParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] int32 extras ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayDefaultParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] int32 extras ) cil managed { .param [1] = int32(3) .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParamsNotLast_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] object[] extras, [opt] int32 a ) cil managed { .param [1] = nullref .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_01() { string source = @" class P { void M(System.IDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ System.IDisposable GetDisposable() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( System.IDisposable P.GetDisposable()) (OperationKind.Invocation, Type: System.IDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_02() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } class MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_03() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable() : input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } struct MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_04() { string source = @" class P { void M<MyDisposable>(MyDisposable input, bool b) where MyDisposable : System.IDisposable /*<bind>*/{ using (b ? GetDisposable<MyDisposable>() : input) { b = true; } }/*</bind>*/ T GetDisposable<T>() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposab ... sposable>()') Value: IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposab ... sposable>()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposab ... Disposable>') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_05() { string source = @" class P { void M(MyDisposable? input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable? GetDisposable() => throw null; } struct MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_06() { string source = @" class P { void M(dynamic input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ dynamic GetDisposable() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( dynamic P.GetDisposable()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable() ?? input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Finalizing: {R6} Leaving: {R5} {R4} {R1} } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_07() { string source = @" class P { void M(NotDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ NotDisposable GetDisposable() => throw null; } class NotDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( NotDisposable P.GetDisposable()) (OperationKind.Invocation, Type: NotDisposable, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: NotDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'NotDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (GetDisposable() ?? input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("NotDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_08() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable() : input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } struct MyDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (b ? GetDisposable() : input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable() : input").WithArguments("MyDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_09() { string source = @" class P { void M<MyDisposable>(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable<MyDisposable>() : input) { b = true; } }/*</bind>*/ T GetDisposable<T>() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... sposable>()') Value: IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposab ... sposable>()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... Disposable>') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Unboxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (b ? GetDisposable<MyDisposable>() : input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable<MyDisposable>() : input").WithArguments("MyDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_10() { string source = @" class P { void M(MyDisposable? input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable? GetDisposable() => throw null; } struct MyDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable?': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (GetDisposable() ?? input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("MyDisposable?").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_11() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (var x = GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } class MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { Locals: [MyDisposable x] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Finalizing: {R6} Leaving: {R5} {R4} {R1} } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_12() { string source = @" class P { void M(dynamic input1, dynamic input2, bool b) /*<bind>*/{ using (dynamic x = input1, y = input2) { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [dynamic x] [dynamic y] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x = input1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Next (Regular) Block[B3] Entering: {R3} {R4} .try {R3, R4} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input2') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y = input2') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Next (Regular) Block[B5] Entering: {R6} {R7} .try {R6, R7} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B12] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R8} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = input2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = input2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } .finally {R9} { Block[B9] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = input1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = input1') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } Block[B12] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_13() { string source = @" class P { void M(System.IDisposable input, object o) /*<bind>*/{ using (input) { o?.ToString(); } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Arguments(0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_14() { string source = @" class P : System.IDisposable { public void Dispose() { } void M(System.IDisposable input, P p) /*<bind>*/{ using (p = M2(out int c)) { c = 1; } }/*</bind>*/ P M2(out int c) { c = 0; return new P(); } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 c] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p = M2(out int c)') Value: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p') Right: IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'p = M2(out int c)') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'p = M2(out int c)') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'p = M2(out int c)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_15() { string source = @" class P { void M(System.IDisposable input, object o) /*<bind>*/{ using (input) { o?.ToString(); } }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Arguments(0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_16() { string source = @" class P { void M() /*<bind>*/{ using (null) { } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'null') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingFlow_17() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C { async Task M(S? s) /*<bind>*/{ await using (s) { } }/*</bind>*/ } struct S { public Task DisposeAsync() { return default; } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 's') Value: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: S?, IsInvalid) (Syntax: 's') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 's') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 's') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // (9,22): error CS8410: 'S?': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. // await using (s) Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "s").WithArguments("S?").WithLocation(9, 22) }; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_18() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, bool b = false) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false])) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_19() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, bool b = false, params int[] extras) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false], params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_20() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(params int[] extras) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync(params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_21() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 'this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 'this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'C.DisposeAsync(int, params int[], bool)' // await using(this){} Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this").WithArguments("extras", "C.DisposeAsync(int, params int[], bool)").WithLocation(8, 21), // file.cs(8,21): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. // await using(this){} Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "this").WithArguments("C").WithLocation(8, 21), // file.cs(11,34): error CS0231: A params parameter must be the last parameter in a formal parameter list // Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null; Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] extras").WithLocation(11, 34) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_01() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using var x = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_02() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = new P(), y = new P(), z = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] [P y] [P z] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'z = new P()') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R6} {R7} .try {R6, R7} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B14] Finalizing: {R8} {R9} {R10} Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R8} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z = new P()') Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'z = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'z = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Arguments(0) Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B8] [B9] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R10} { Block[B11] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B14] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_03() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = null ?? new P(), y = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { Locals: [P x] [P y] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()') Value: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B6] Entering: {R6} {R7} .try {R6, R7} { Block[B6] - Block Predecessors: [B5] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R5} {R4} {R1} } .finally {R8} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = null ?? new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = null ?? new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = null ?? new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_04() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = new P(), y = null ?? new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] [P y] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} {R4} {R5} .try {R2, R3} { .locals {R4} { CaptureIds: [1] .locals {R5} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()') Value: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()') Next (Regular) Block[B6] Leaving: {R4} Entering: {R6} {R7} } .try {R6, R7} { Block[B6] - Block Predecessors: [B5] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R3} {R2} {R1} } .finally {R8} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = null ?? new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = null ?? new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = null ?? new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_05() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; using var e = new P(); int f = 3; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_06() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; System.Action lambda = () => { _ = c.ToString(); }; using var e = new P(); int f = 3; lambda(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [System.Action lambda] [P e] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }') Left: ILocalReferenceOperation: lambda (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { _ = ... String(); }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { _ = ... String(); }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = c.ToString();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '_ = c.ToString()') Left: IDiscardOperation (Symbol: System.String _) (OperationKind.Discard, Type: System.String) (Syntax: '_') Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'lambda();') Expression: IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'lambda()') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Action) (Syntax: 'lambda') Arguments(0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_07() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; using var b = new P(); { int c = 1; using var d = new P(); int e = 2; } int f = 3; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [P b] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} {R4} .try {R2, R3} { .locals {R4} { Locals: [System.Int32 c] [P d] [System.Int32 e] Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R5} {R6} .try {R5, R6} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B7] Finalizing: {R7} Leaving: {R6} {R5} {R4} } .finally {R7} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B11] Finalizing: {R8} Leaving: {R3} {R2} {R1} } .finally {R8} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B8] [B9] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B11] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_08() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; using var b = new P(); label1: { int c = 1; if (a > 0) goto label1; using var d = new P(); if (a > 0) goto label1; int e = 2; } int f = 3; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [P b] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] [B5] [B10] Statements (0) Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [System.Int32 c] [P d] [System.Int32 e] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R4} Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R5} {R6} .try {R5, R6} { Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Finalizing: {R7} Leaving: {R6} {R5} {R4} Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B10] Finalizing: {R7} Leaving: {R6} {R5} {R4} } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] } .finally {R8} { Block[B11] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B14] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_09() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C { public Task DisposeAsync() { return default; } async Task M() /*<bind>*/{ await using var c = new C(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'c = new C()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_10() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C : System.IDisposable { public Task DisposeAsync() { return default; } public void Dispose() { } async Task M() /*<bind>*/{ using var c = new C(); await using var d = new C(); using var e = new C(); await using var f = new C(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] [C d] [C e] [C f] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'd = new C()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'e = new C()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R6} {R7} .try {R6, R7} { Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'f = new C()') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R8} {R9} .try {R8, R9} { Block[B5] - Block Predecessors: [B4] Statements (0) Next (Regular) Block[B18] Finalizing: {R10} {R11} {R12} {R13} Leaving: {R9} {R8} {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R10} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'f = new C()') Operand: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'f = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'f = new C()') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R11} { Block[B9] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new C()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new C()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R12} { Block[B12] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new C()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'd = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'd = new C()') Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Arguments(0) Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R13} { Block[B15] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new C()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Arguments(0) Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B18] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_11() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; using var e = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_12() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; label1: using var c = new P(); int d = 2; label2: label3: using var e = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_13() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ if (true) label1: using var a = new P(); if (true) label2: label3: using var b = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B7] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [P a] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B13] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Entering: {R5} .locals {R5} { Locals: [P b] Block[B8] - Block Predecessors: [B7] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B9] Entering: {R6} {R7} .try {R6, R7} { Block[B9] - Block Predecessors: [B8] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} Leaving: {R7} {R6} {R5} } .finally {R8} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B7] [B9] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label1: Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label1: using var a = new P();").WithLocation(12, 13), // file.cs(15,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label2: Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label2: label3: using var b = new P();").WithLocation(15, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_14() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ goto label1; int x = 0; label1: using var a = this; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B0] [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,9): warning CS0162: Unreachable code detected // int x = 0; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_15() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ label1: using var a = this; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P a] Block[B1] - Block Predecessors: [B0] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B1] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(13,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(13, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_16() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ goto label1; int x = 0; label1: using var a = this; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B0] [B1] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B2] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,9): warning CS0162: Unreachable code detected // int x = 0; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9), // file.cs(15,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(15, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_17() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ if (b) goto label1; int x = 0; label1: using var a = this; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_18() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ label1: using var a = this; if (b) goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P a] Block[B1] - Block Predecessors: [B0] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B1] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(14,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(14, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_19() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ if (b) goto label1; int x = 0; label1: using var a = this; if (b) goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B8] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(17,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_20() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 ref struct P { public void Dispose() { } void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void P.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_21() { string source = @" ref struct P { public object Dispose() => null; void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,13): warning CS0280: 'P' does not implement the 'disposable' pattern. 'P.Dispose()' has the wrong signature. // using var x = new P(); Diagnostic(ErrorCode.WRN_PatternBadSignature, "using var x = new P();").WithArguments("P", "disposable", "P.Dispose()").WithLocation(8, 13), // file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var x = new P(); Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_22() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 ref struct P { public void Dispose(int a = 1, bool b = true, params object[] extras) { } void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void P.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var x = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var x = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var x = new P();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var x = new P();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var x = new P();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_23() { string source = @" using System.Threading.Tasks; class P { public virtual Task DisposeAsync() => throw null; async Task M(bool b) /*<bind>*/{ await using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Expression: IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_24() { string source = @" using System.Threading.Tasks; class P { public virtual Task DisposeAsync(int a = 1, bool b = true, params object[] extras) => throw null; async Task M(bool b) /*<bind>*/{ await using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Expression: IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'await using ... = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'await using ... = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'await using ... = new P();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using ... = new P();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using var c = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclarations() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ using var c = new C(); using var d = new C(); using var e = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var d = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var d = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var e = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var e = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_MultipleVariables() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using C c = new C(), d = new C(), e = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = ... = new C();') IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null"; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclaration_WithLabels() { string source = @" using System; #pragma warning disable CS0164 class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ label1: using var a = new C(); label2: label3: using var b = new C(); }/*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C a Local_2: C b ILabeledOperation (Label: label1) (OperationKind.Labeled, Type: null) (Syntax: 'label1: ... = new C();') Statement: IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var a = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var a = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null ILabeledOperation (Label: label2) (OperationKind.Labeled, Type: null) (Syntax: 'label2: ... = new C();') Statement: ILabeledOperation (Label: label3) (OperationKind.Labeled, Type: null) (Syntax: 'label3: ... = new C();') Statement: IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var b = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var b = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() { /*<bind>*/await using var c = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclarations_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() /*<bind>*/{ await using var c = new C(); await using var d = new C(); await using var e = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_MultipleVariables_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() { /*<bind>*/await using C c = new C(), d = new C(), e = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_RegularAsync_Mix() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C : IDisposable { public Task DisposeAsync() { return default; } public void Dispose() { } public static async Task M1() /*<bind>*/{ using C c = new C(); await using C d = new C(); using C e = new C(), f = new C(); await using C g = new C(), h = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (4 statements, 6 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e Local_4: C f Local_5: C g Local_6: C h IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C e = ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C e = ... = new C();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C e = new C ... f = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C g = new C ... h = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C g) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'g = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C h) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'h = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void UsingDeclaration_DefaultDisposeArguments() { string source = @" class C { public static void M1() { /*<bind>*/using var s = new S();/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False, DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var s = new S();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var s = new S();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var s = new S();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var s = new S();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var s = new S();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var s = new S();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var s = new S();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingDeclaration_LocalFunctionDefinedAfterUsingReferenceBeforeUsing() { var comp = CreateCompilation(@" using System; class C { void M() /*<bind>*/{ localFunc2(); static void localFunc() {} using IDisposable i = null; localFunc(); static void localFunc2() {} localFunc3(); static void localFunc3() {} }/*</bind>*/ } "); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (7 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.IDisposable i IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();') Expression: IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... alFunc() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null') Declarators: IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();') Expression: IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc2()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc2() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();') Expression: IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc3()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc3() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ", DiagnosticDescription.None); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IDisposable i] Methods: [void localFunc()] [void localFunc2()] [void localFunc3()] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();') Expression: IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();') Expression: IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();') Expression: IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null') Instance Receiver: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } { void localFunc() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Exit Predecessors: [B0#0R1] Statements (0) } { void localFunc2() Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Block[B1#1R1] - Exit Predecessors: [B0#1R1] Statements (0) } { void localFunc3() Block[B0#2R1] - Entry Statements (0) Next (Regular) Block[B1#2R1] Block[B1#2R1] - Exit Predecessors: [B0#2R1] Statements (0) } } Block[B6] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void UsingDeclaration_LocalDefinedAfterUsingReferenceBeforeUsing() { var comp = CreateCompilation(@" using System; class C { void M() /*<bind>*/{ _ = local; using IDisposable i = null; object local = null; }/*</bind>*/ } "); var expectedDiagnostics = new DiagnosticDescription[] { // (8,13): error CS0841: Cannot use local variable 'local' before it is declared // _ = local; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "local").WithArguments("local").WithLocation(8, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (3 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') Locals: Local_1: System.IDisposable i Local_2: System.Object local IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local') IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null') Declarators: IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'object local = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'object local = null') Declarators: IVariableDeclaratorOperation (Symbol: System.Object local) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'local = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null ", expectedDiagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IDisposable i] [System.Object local] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'local = null') Left: ILocalReferenceOperation: local (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'local = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null') Instance Receiver: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void UsingDeclaration_InsideSwitchCaseEmbeddedStatements() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(int x) /*<bind>*/{ switch (x) { case 5: using C1 o1 = new C1(); break; } }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(14,17): error CS8647: A using variable cannot be used directly within a switch section (consider using braces). // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(14, 17) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [C1 o1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '5') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } Block[B8] - Exit Predecessors: [B2] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideIfEmbeddedStatement() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(bool b) /*<bind>*/{ if (b) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(12, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [C1 o1] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideForEmbeddedStatement() { var source = @" using System; using System.Collections; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M() /*<bind>*/{ for (;;) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C1 o1] Block[B1] - Block Predecessors: [B0] [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B1] Entering: {R1} Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideForEachEmbeddedStatement() { var source = @" using System; using System.Collections; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(IEnumerable e) /*<bind>*/{ foreach (var o in e) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e') Value: IInvocationOperation (virtual System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'e') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) Operand: IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'e') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B12] IInvocationOperation (virtual System.Boolean System.Collections.IEnumerator.MoveNext()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'e') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Arguments(0) Finalizing: {R9} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [System.Object o] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'var') Left: ILocalReferenceOperation: o (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'var') Right: IPropertyReferenceOperation: System.Object System.Collections.IEnumerator.Current { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'var') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { Locals: [C1 o1] Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R6} {R7} .try {R6, R7} { Block[B5] - Block Predecessors: [B4] Statements (0) Next (Regular) Block[B2] Finalizing: {R8} Leaving: {R7} {R6} {R5} {R4} } .finally {R8} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } } .finally {R9} { CaptureIds: [1] Block[B9] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B12] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, 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_IUsingStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_SimpleUsingNewVariable() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c = new C()) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.AsyncStreams)] [Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")] public void IUsingAwaitStatement_SimpleAwaitUsing() { string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { public static async Task M1(IAsyncDisposable disposable) { /*<bind>*/await using (var c = disposable) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (IsAsynchronous) (OperationKind.Using, Type: null) (Syntax: 'await using ... }') Locals: Local_1: System.IAsyncDisposable c Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c = disposable') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = disposable') Declarators: IVariableDeclaratorOperation (Symbol: System.IAsyncDisposable c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = disposable') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= disposable') IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable') Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.AsyncStreams)] [Fact, WorkItem(30362, "https://github.com/dotnet/roslyn/issues/30362")] public void UsingFlow_SimpleAwaitUsing() { string source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { public static async Task M1(IAsyncDisposable disposable) /*<bind>*/{ await using (var c = disposable) { Console.WriteLine(c.ToString()); } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IAsyncDisposable c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Right: IParameterReferenceOperation: disposable (OperationKind.ParameterReference, Type: System.IAsyncDisposable) (Syntax: 'disposable') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = disposable') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = disposable') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsImplicit) (Syntax: 'c = disposable') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.IAsyncDisposable, IsImplicit) (Syntax: 'c = disposable') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_MultipleNewVariable() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (C c1 = new C(), c2 = new C()) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (C c1 ... }') Locals: Local_1: C c1 Local_2: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C c1 = new ... 2 = new C()') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c1 = new ... 2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_SimpleUsingStatementExistingResource() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c = new C(); /*<bind>*/using (c) { Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c) ... }') Resources: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NestedUsingNewResources() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c1 = new C()) using (var c2 = new C()) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c1 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (var ... }') Locals: Local_1: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var c2 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NestedUsingExistingResources() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c1 = new C(); var c2 = new C(); /*<bind>*/using (c1) using (c2) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c1) ... }') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Body: IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (c2) ... }') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidMultipleVariableDeclaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (var c1 = new C(), c2 = new C()) { Console.WriteLine(c1.ToString() + c2.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Local_2: C c2 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = ne ... 2 = new C()') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = ne ... 2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/using (var c1 = new C(), c2 = new C()) Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C(), c2 = new C()").WithLocation(12, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IOperationTests_MultipleExistingResourcesPassed() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ var c1 = new C(); var c2 = new C(); using (c1, c2) { Console.WriteLine(c1.ToString() + c2.ToString()); } }/*</bind>*/ } "; // Capturing the whole block here, to show that the using statement is actually being bound as a using statement, followed by // an expression and a separate block, rather than being bound as a using statement with an invalid expression as the resources string expectedOperationTree = @" IBlockOperation (5 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') Locals: Local_1: C c1 Local_2: C c2 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c1 = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var c2 = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c2 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1') Body: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c2') Expression: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c2') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString ... .ToString()') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'c1.ToString ... .ToString()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c2.ToString()') Instance Receiver: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: C) (Syntax: 'c2') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // using (c1, c2) Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(14, 18), // CS1525: Invalid expression term ',' // using (c1, c2) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(14, 18), // CS1002: ; expected // using (c1, c2) Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(14, 18), // CS1513: } expected // using (c1, c2) Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(14, 18), // CS1002: ; expected // using (c1, c2) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(14, 22), // CS1513: } expected // using (c1, c2) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(14, 22) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidNonDisposableNewResource() { string source = @" using System; class C { public static void M1() { /*<bind>*/using (var c1 = new C()) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (var ... }') Locals: Local_1: C c1 Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var c1 = new C()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var c1 = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable' // /*<bind>*/using (var c1 = new C()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var c1 = new C()").WithArguments("C").WithLocation(9, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidNonDisposableExistingResource() { string source = @" using System; class C { public static void M1() { var c1 = new C(); /*<bind>*/using (c1) { Console.WriteLine(c1.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using (c1) ... }') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c1.ToString()') Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C) (Syntax: 'c1') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable' // /*<bind>*/using (c1) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1").WithArguments("C").WithLocation(10, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_InvalidEmptyUsingResources() { string source = @" using System; class C { public static void M1() { /*<bind>*/using () { }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using () ... }') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // /*<bind>*/using () Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 26) }; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingWithoutSavedReference() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using (GetC()) { }/*</bind>*/ } public static C GetC() => new C(); } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (GetC ... }') Resources: IInvocationOperation (C C.GetC()) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DynamicArgument() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { dynamic d = null; /*<bind>*/using (d) { Console.WriteLine(d); }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (d) ... }') Resources: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Console.WriteLine(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""WriteLine"", Containing Type: System.Console) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Console.WriteLine') Type Arguments(0) Instance Receiver: null Arguments(1): ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_NullResource() { string source = @" using System; class C { public static void M1() { /*<bind>*/using (null) { }/*</bind>*/ } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (null ... }') Resources: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_Declaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (/*<bind>*/var c = new C()/*</bind>*/) { Console.WriteLine(c.ToString()); } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_StatementSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (var c = new C()) /*<bind>*/{ Console.WriteLine(c.ToString()); }/*</bind>*/ } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... oString());') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ToString())') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.ToString()') IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_ExpressionSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { var c = new C(); using (/*<bind>*/c/*</bind>*/) { Console.WriteLine(c.ToString()); } } } "; string expectedOperationTree = @" ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_UsingStatementSyntax_VariableDeclaratorSyntax() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { using (C /*<bind>*/c1 = new C()/*</bind>*/, c2 = new C()) { Console.WriteLine(c1.ToString()); } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: C c1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1 = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_OutVarInResource() { string source = @" class P : System.IDisposable { public void Dispose() { } void M(P p) { /*<bind>*/using (p = M2(out int c)) { c = 1; }/*</bind>*/ } P M2(out int c) { c = 0; return new P(); } } "; string expectedOperationTree = @" IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'using (p = ... }') Locals: Local_1: System.Int32 c Resources: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p') Right: IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DefaultDisposeArguments() { string source = @" class C { public static void M1() { /*<bind>*/using(var s = new S()) { }/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(var s ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(var s ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_ExpressionDefaultDisposeArguments() { string source = @" class C { public static void M1() { var s = new S(); /*<bind>*/using(s) { }/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingOperation (DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.Using, Type: null) (Syntax: 'using(s) ... }') Resources: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using(s) ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using(s) ... }') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(s) ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(s) ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(s) ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(s) ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<UsingStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParams() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } ref struct S { public void Dispose(params object[] extras = null) { } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()') Instance Receiver: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(19,25): error CS1751: Cannot specify a default value for a parameter array // public void Dispose(params object[] extras = null) { } Diagnostic(ErrorCode.ERR_DefaultValueForParamsParameter, "params").WithLocation(19, 25) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } //THEORY: we won't ever call a params in normal form, because we ignore the default value in metadata. // So: it's either a valid params parameter, in which case we call it in the extended way. // Or its an invalid params parameter, in which case we can't use it, and we error out. // Interestingly we check params before we check default, so a params int = 3 will be callable with an // argument, but not without. [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] object[] extras ) cil managed { .param [1] = nullref .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("C.M2", @" { // Code size 21 (0x15) .maxstack 2 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: call ""object[] System.Array.Empty<object>()"" IL_000f: call ""void S.Dispose(params object[])"" IL_0014: ret } "); verifier.VerifyIL("C.M1", @" { // Code size 24 (0x18) .maxstack 2 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" .try { IL_0008: leave.s IL_0017 } finally { IL_000a: ldloca.s V_0 IL_000c: call ""object[] System.Array.Empty<object>()"" IL_0011: call ""void S.Dispose(params object[])"" IL_0016: endfinally } IL_0017: ret } "); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IUsingOperation (DisposeMethod: void S.Dispose(params System.Object[] extras)) (OperationKind.Using, Type: null) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') DisposeArguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void S.Dispose(params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's = new S()') Instance Receiver: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsImplicit) (Syntax: 's = new S()') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using(var s ... }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using(var s ... }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using(var s ... }') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using(var s ... }') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( int32 extras ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayOptionalParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] int32 extras ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithNonArrayDefaultParams_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); s.Dispose(1); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] int32 extras ) cil managed { .param [1] = int32(3) .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IUsingStatement_DisposalWithDefaultParamsNotLast_Metadata() { string source = @" class C { public static void M1() /*<bind>*/{ using(var s = new S()) { } }/*</bind>*/ public static void M2() { var s = new S(); s.Dispose(); } } "; var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig instance void Dispose ( [opt] object[] extras, [opt] int32 a ) cil managed { .param [1] = nullref .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .maxstack 8 IL_0000: nop IL_0001: ret } } "; var ilReference = CreateMetadataReferenceFromIlSource(ilSource); var expectedDiagnostics = new[] { // (6,15): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)' // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(6, 15), // (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using(var s = new S()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15), // (14,11): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'S.Dispose(params object[], int)' // s.Dispose(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Dispose").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(14, 11) }; var compilation = CreateCompilationWithIL(source, ilSource); compilation.VerifyDiagnostics(expectedDiagnostics); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'using(var s ... }') Locals: Local_1: S s Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'var s = new S()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(compilation, expectedOperationTree, expectedDiagnostics); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [S s] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Left: ILocalReferenceOperation: s (IsDeclaration: True) (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Right: IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S, IsInvalid) (Syntax: 'new S()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's = new S()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 's = new S()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S, IsInvalid, IsImplicit) (Syntax: 's = new S()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_01() { string source = @" class P { void M(System.IDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ System.IDisposable GetDisposable() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( System.IDisposable P.GetDisposable()) (OperationKind.Invocation, Type: System.IDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_02() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } class MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_03() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable() : input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } struct MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_04() { string source = @" class P { void M<MyDisposable>(MyDisposable input, bool b) where MyDisposable : System.IDisposable /*<bind>*/{ using (b ? GetDisposable<MyDisposable>() : input) { b = true; } }/*</bind>*/ T GetDisposable<T>() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposab ... sposable>()') Value: IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposab ... sposable>()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposab ... Disposable>') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_05() { string source = @" class P { void M(MyDisposable? input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable? GetDisposable() => throw null; } struct MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_06() { string source = @" class P { void M(dynamic input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ dynamic GetDisposable() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( dynamic P.GetDisposable()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable() ?? input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Finalizing: {R6} Leaving: {R5} {R4} {R1} } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_07() { string source = @" class P { void M(NotDisposable input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ NotDisposable GetDisposable() => throw null; } class NotDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( NotDisposable P.GetDisposable()) (OperationKind.Invocation, Type: NotDisposable, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: NotDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: NotDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'NotDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (GetDisposable() ?? input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("NotDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_08() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable() : input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } struct MyDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... e() : input') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (b ? GetDisposable() : input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable() : input").WithArguments("MyDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_09() { string source = @" class P { void M<MyDisposable>(MyDisposable input, bool b) /*<bind>*/{ using (b ? GetDisposable<MyDisposable>() : input) { b = true; } }/*</bind>*/ T GetDisposable<T>() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... sposable>()') Value: IInvocationOperation ( MyDisposable P.GetDisposable<MyDisposable>()) (OperationKind.Invocation, Type: MyDisposable, IsInvalid) (Syntax: 'GetDisposab ... sposable>()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposab ... Disposable>') Arguments(0) Next (Regular) Block[B4] Entering: {R2} {R3} Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Unboxing) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsInvalid, IsImplicit) (Syntax: 'b ? GetDisp ... >() : input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (b ? GetDisposable<MyDisposable>() : input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "b ? GetDisposable<MyDisposable>() : input").WithArguments("MyDisposable").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_10() { string source = @" class P { void M(MyDisposable? input, bool b) /*<bind>*/{ using (GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable? GetDisposable() => throw null; } struct MyDisposable { } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable? P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable?, IsInvalid) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R2} Entering: {R3} {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable?, IsInvalid) (Syntax: 'input') Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable?, IsInvalid, IsImplicit) (Syntax: 'GetDisposable() ?? input') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(6,16): error CS1674: 'MyDisposable?': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (GetDisposable() ?? input) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "GetDisposable() ?? input").WithArguments("MyDisposable?").WithLocation(6, 16) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_11() { string source = @" class P { void M(MyDisposable input, bool b) /*<bind>*/{ using (var x = GetDisposable() ?? input) { b = true; } }/*</bind>*/ MyDisposable GetDisposable() => throw null; } class MyDisposable : System.IDisposable { public void Dispose() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { Locals: [MyDisposable x] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IInvocationOperation ( MyDisposable P.GetDisposable()) (OperationKind.Invocation, Type: MyDisposable) (Syntax: 'GetDisposable()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'GetDisposable') Arguments(0) Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetDisposable()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetDisposable()') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable()') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyDisposable) (Syntax: 'input') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyDisposable, IsImplicit) (Syntax: 'GetDisposable() ?? input') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Finalizing: {R6} Leaving: {R5} {R4} {R1} } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: MyDisposable, IsImplicit) (Syntax: 'x = GetDisp ... () ?? input') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_12() { string source = @" class P { void M(dynamic input1, dynamic input2, bool b) /*<bind>*/{ using (dynamic x = input1, y = input2) { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [dynamic x] [dynamic y] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x = input1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'x = input1') Next (Regular) Block[B3] Entering: {R3} {R4} .try {R3, R4} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input2') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y = input2') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitDynamic) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic, IsImplicit) (Syntax: 'y = input2') Next (Regular) Block[B5] Entering: {R6} {R7} .try {R6, R7} { Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B12] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R8} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = input2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = input2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'y = input2') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } .finally {R9} { Block[B9] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = input1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = input1') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x = input1') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } Block[B12] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_13() { string source = @" class P { void M(System.IDisposable input, object o) /*<bind>*/{ using (input) { o?.ToString(); } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Arguments(0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_14() { string source = @" class P : System.IDisposable { public void Dispose() { } void M(System.IDisposable input, P p) /*<bind>*/{ using (p = M2(out int c)) { c = 1; } }/*</bind>*/ P M2(out int c) { c = 0; return new P(); } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 c] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p = M2(out int c)') Value: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P) (Syntax: 'p = M2(out int c)') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: P) (Syntax: 'p') Right: IInvocationOperation ( P P.M2(out System.Int32 c)) (OperationKind.Invocation, Type: P) (Syntax: 'M2(out int c)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'p = M2(out int c)') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'p = M2(out int c)') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'p = M2(out int c)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'p = M2(out int c)') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_15() { string source = @" class P { void M(System.IDisposable input, object o) /*<bind>*/{ using (input) { o?.ToString(); } }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.IDisposable) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'o?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o') Arguments(0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'input') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_16() { string source = @" class P { void M() /*<bind>*/{ using (null) { } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'null') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingFlow_17() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C { async Task M(S? s) /*<bind>*/{ await using (s) { } }/*</bind>*/ } struct S { public Task DisposeAsync() { return default; } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 's') Value: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: S?, IsInvalid) (Syntax: 's') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 's') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 's') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 's') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: S?, IsInvalid, IsImplicit) (Syntax: 's') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // (9,22): error CS8410: 'S?': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. // await using (s) Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "s").WithArguments("S?").WithLocation(9, 22) }; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_18() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, bool b = false) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false])) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_19() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, bool b = false, params int[] extras) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync([System.Int32 a = 3], [System.Boolean b = false], params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'await using(this){}') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_20() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(params int[] extras) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync(params System.Int32[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'this') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using(this){}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'await using(this){}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using(this){}') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using(this){}') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingFlow_21() { string source = @" using System; using System.Threading.Tasks; public class C { public async Task M() /*<bind>*/{ await using(this){} }/*</bind>*/ Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'this') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'this') Expression: IInvocationOperation (virtual System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.ValueTask, IsInvalid, IsImplicit) (Syntax: 'this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IAsyncDisposable, IsInvalid, IsImplicit) (Syntax: 'this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'extras' of 'C.DisposeAsync(int, params int[], bool)' // await using(this){} Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this").WithArguments("extras", "C.DisposeAsync(int, params int[], bool)").WithLocation(8, 21), // file.cs(8,21): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. // await using(this){} Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "this").WithArguments("C").WithLocation(8, 21), // file.cs(11,34): error CS0231: A params parameter must be the last parameter in a formal parameter list // Task DisposeAsync(int a = 3, params int[] extras, bool b = false) => throw null; Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] extras").WithLocation(11, 34) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_01() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using var x = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_02() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = new P(), y = new P(), z = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] [P y] [P z] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'z = new P()') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R6} {R7} .try {R6, R7} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B14] Finalizing: {R8} {R9} {R10} Leaving: {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R8} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z = new P()') Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'z = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'z = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'z = new P()') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Arguments(0) Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B8] [B9] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R10} { Block[B11] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B14] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_03() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = null ?? new P(), y = new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { Locals: [P x] [P y] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()') Value: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} {R5} } .try {R4, R5} { Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B6] Entering: {R6} {R7} .try {R6, R7} { Block[B6] - Block Predecessors: [B5] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R5} {R4} {R1} } .finally {R8} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = null ?? new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = null ?? new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = null ?? new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = null ?? new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_04() { string source = @" using System; class P : IDisposable { void M() /*<bind>*/{ using P x = new P(), y = null ?? new P(); }/*</bind>*/ public void Dispose() { } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] [P y] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} {R4} {R5} .try {R2, R3} { .locals {R4} { CaptureIds: [1] .locals {R5} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: P, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new P()') Value: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: P, IsImplicit) (Syntax: 'null ?? new P()') Next (Regular) Block[B6] Leaving: {R4} Entering: {R6} {R7} } .try {R6, R7} { Block[B6] - Block Predecessors: [B5] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} {R9} Leaving: {R7} {R6} {R3} {R2} {R1} } .finally {R8} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y = null ?? new P()') Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y = null ?? new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'y = null ?? new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'y = null ?? new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R9} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_05() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; using var e = new P(); int f = 3; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_06() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; System.Action lambda = () => { _ = c.ToString(); }; using var e = new P(); int f = 3; lambda(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [System.Action lambda] [P e] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }') Left: ILocalReferenceOperation: lambda (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Action, IsImplicit) (Syntax: 'lambda = () ... String(); }') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { _ = ... String(); }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { _ = ... String(); }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = c.ToString();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '_ = c.ToString()') Left: IDiscardOperation (Symbol: System.String _) (OperationKind.Discard, Type: System.String) (Syntax: '_') Right: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'c.ToString()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'lambda();') Expression: IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'lambda()') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Action) (Syntax: 'lambda') Arguments(0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_07() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; using var b = new P(); { int c = 1; using var d = new P(); int e = 2; } int f = 3; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [P b] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} {R4} .try {R2, R3} { .locals {R4} { Locals: [System.Int32 c] [P d] [System.Int32 e] Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R5} {R6} .try {R5, R6} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B7] Finalizing: {R7} Leaving: {R6} {R5} {R4} } .finally {R7} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B11] Finalizing: {R8} Leaving: {R3} {R2} {R1} } .finally {R8} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B8] [B9] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B11] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_08() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; using var b = new P(); label1: { int c = 1; if (a > 0) goto label1; using var d = new P(); if (a > 0) goto label1; int e = 2; } int f = 3; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [P b] [System.Int32 f] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] [B5] [B10] Statements (0) Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [System.Int32 c] [P d] [System.Int32 e] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R4} Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'd = new P()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R5} {R6} .try {R5, R6} { Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'a > 0') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Finalizing: {R7} Leaving: {R6} {R5} {R4} Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B10] Finalizing: {R7} Leaving: {R6} {R5} {R4} } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new P()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'd = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'd = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'd = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] } .finally {R8} { Block[B11] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B14] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_09() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C { public Task DisposeAsync() { return default; } async Task M() /*<bind>*/{ await using var c = new C(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'c = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'c = new C()') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_10() { string source = @" #pragma warning disable CS0815, CS0219 using System.Threading.Tasks; class C : System.IDisposable { public Task DisposeAsync() { return default; } public void Dispose() { } async Task M() /*<bind>*/{ using var c = new C(); await using var d = new C(); using var e = new C(); await using var f = new C(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] [C d] [C e] [C f] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'd = new C()') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'e = new C()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R6} {R7} .try {R6, R7} { Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'f = new C()') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R8} {R9} .try {R8, R9} { Block[B5] - Block Predecessors: [B4] Statements (0) Next (Regular) Block[B18] Finalizing: {R10} {R11} {R12} {R13} Leaving: {R9} {R8} {R7} {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R10} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'f = new C()') Operand: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'f = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'f = new C()') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'f = new C()') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R11} { Block[B9] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new C()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new C()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'e = new C()') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R12} { Block[B12] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd = new C()') Operand: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'd = new C()') Expression: IInvocationOperation ( System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'd = new C()') Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'd = new C()') Arguments(0) Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R13} { Block[B15] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new C()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new C()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Arguments(0) Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B18] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_Flow_11() { string source = @" #pragma warning disable CS0815, CS0219 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; using var c = new P(); int d = 2; using var e = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_12() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ int a = 0; int b = 1; label1: using var c = new P(); int d = 2; label2: label3: using var e = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [P c] [System.Int32 d] [P e] Block[B1] - Block Predecessors: [B0] Statements (3) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'c = new P()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'e = new P()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B10] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e = new P()') Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'e = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B7] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c = new P()') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'c = new P()') Arguments(0) Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B10] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_13() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ if (true) label1: using var a = new P(); if (true) label2: label3: using var b = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B7] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [P a] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'a = new P()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B13] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B8] Entering: {R5} .locals {R5} { Locals: [P b] Block[B8] - Block Predecessors: [B7] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B9] Entering: {R6} {R7} .try {R6, R7} { Block[B9] - Block Predecessors: [B8] Statements (0) Next (Regular) Block[B13] Finalizing: {R8} Leaving: {R7} {R6} {R5} } .finally {R8} { Block[B10] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'b = new P()') Arguments(0) Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B10] [B11] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B13] - Exit Predecessors: [B7] [B9] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label1: Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label1: using var a = new P();").WithLocation(12, 13), // file.cs(15,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label2: Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, @"label2: label3: using var b = new P();").WithLocation(15, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_14() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ goto label1; int x = 0; label1: using var a = this; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B0] [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,9): warning CS0162: Unreachable code detected // int x = 0; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_15() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ label1: using var a = this; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P a] Block[B1] - Block Predecessors: [B0] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B1] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(13,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(13, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_16() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M() /*<bind>*/{ goto label1; int x = 0; label1: using var a = this; goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B0] [B1] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B2] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(12,9): warning CS0162: Unreachable code detected // int x = 0; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(12, 9), // file.cs(15,9): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(15, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_17() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ if (b) goto label1; int x = 0; label1: using var a = this; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B8] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_18() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ label1: using var a = this; if (b) goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P a] Block[B1] - Block Predecessors: [B0] [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B1] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(14,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(14, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_19() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 class P : System.IDisposable { public void Dispose() { } void M(bool b) /*<bind>*/{ if (b) goto label1; int x = 0; label1: using var a = this; if (b) goto label1; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] [P a] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'a = this') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Right: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Next (Regular) Block[B4] Entering: {R2} {R3} .try {R2, R3} { Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B8] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Finalizing: {R4} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Finalizing: {R4} Leaving: {R3} {R2} } .finally {R4} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a = this') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'a = this') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'a = this') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'a = this') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[]{ // file.cs(17,13): error CS8649: A goto cannot jump to a location before a using declaration within the same block. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_20() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 ref struct P { public void Dispose() { } void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void P.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_21() { string source = @" ref struct P { public object Dispose() => null; void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,13): warning CS0280: 'P' does not implement the 'disposable' pattern. 'P.Dispose()' has the wrong signature. // using var x = new P(); Diagnostic(ErrorCode.WRN_PatternBadSignature, "using var x = new P();").WithArguments("P", "disposable", "P.Dispose()").WithLocation(8, 13), // file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var x = new P(); Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_22() { string source = @" #pragma warning disable CS0815, CS0219, CS0164 ref struct P { public void Dispose(int a = 1, bool b = true, params object[] extras) { } void M(bool b) /*<bind>*/{ using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B4] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (1) IInvocationOperation ( void P.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var x = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var x = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var x = new P();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var x = new P();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var x = new P();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var x = new P();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (StructuredExceptionHandling) Block[null] } } Block[B4] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_23() { string source = @" using System.Threading.Tasks; class P { public virtual Task DisposeAsync() => throw null; async Task M(bool b) /*<bind>*/{ await using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Expression: IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void UsingDeclaration_Flow_24() { string source = @" using System.Threading.Tasks; class P { public virtual Task DisposeAsync(int a = 1, bool b = true, params object[] extras) => throw null; async Task M(bool b) /*<bind>*/{ await using var x = new P(); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [P x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: P, IsImplicit) (Syntax: 'x = new P()') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Right: IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x = new P()') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IAwaitOperation (OperationKind.Await, Type: System.Void, IsImplicit) (Syntax: 'x = new P()') Expression: IInvocationOperation (virtual System.Threading.Tasks.Task P.DisposeAsync([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] extras)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task, IsImplicit) (Syntax: 'x = new P()') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: P, IsImplicit) (Syntax: 'x = new P()') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'await using ... = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'await using ... = new P();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: extras) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'await using ... = new P();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'await using ... = new P();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'await using ... = new P();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source + s_IAsyncEnumerable + IOperationTests_IForEachLoopStatement.s_ValueTask, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using var c = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclarations() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ using var c = new C(); using var d = new C(); using var e = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var d = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var d = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var e = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var e = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_MultipleVariables() { string source = @" using System; class C : IDisposable { public void Dispose() { } public static void M1() { /*<bind>*/using C c = new C(), d = new C(), e = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = ... = new C();') IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null"; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclaration_WithLabels() { string source = @" using System; #pragma warning disable CS0164 class C : IDisposable { public void Dispose() { } public static void M1() /*<bind>*/{ label1: using var a = new C(); label2: label3: using var b = new C(); }/*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C a Local_2: C b ILabeledOperation (Label: label1) (OperationKind.Labeled, Type: null) (Syntax: 'label1: ... = new C();') Statement: IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var a = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var a = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null ILabeledOperation (Label: label2) (OperationKind.Labeled, Type: null) (Syntax: 'label2: ... = new C();') Statement: ILabeledOperation (Label: label3) (OperationKind.Labeled, Type: null) (Syntax: 'label3: ... = new C();') Statement: IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var b = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var b = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var b = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() { /*<bind>*/await using var c = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_MultipleDeclarations_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() /*<bind>*/{ await using var c = new C(); await using var d = new C(); await using var e = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_SingleDeclaration_MultipleVariables_Async() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C { public Task DisposeAsync() { return default; } public static async Task M1() { /*<bind>*/await using C c = new C(), d = new C(), e = new C();/*</bind>*/ } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (3 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C ... e = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(32100, "https://github.com/dotnet/roslyn/issues/32100")] public void UsingDeclaration_RegularAsync_Mix() { string source = @" using System; using System.Threading.Tasks; namespace System { interface IAsyncDisposable { } } class C : IDisposable { public Task DisposeAsync() { return default; } public void Dispose() { } public static async Task M1() /*<bind>*/{ using C c = new C(); await using C d = new C(); using C e = new C(), f = new C(); await using C g = new C(), h = new C(); } /*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (4 statements, 6 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: C c Local_2: C d Local_3: C e Local_4: C f Local_5: C g Local_6: C h IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C c = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C c = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C c = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C c) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C d = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C d) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using C e = ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using C e = ... = new C();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C e = new C ... f = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C e) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'e = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null IUsingDeclarationOperation(IsAsynchronous: True, DisposeMethod: System.Threading.Tasks.Task C.DisposeAsync()) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'await using ... = new C();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'await using ... = new C();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C g = new C ... h = new C()') Declarators: IVariableDeclaratorOperation (Symbol: C g) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'g = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: C h) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'h = new C()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C()') IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void UsingDeclaration_DefaultDisposeArguments() { string source = @" class C { public static void M1() { /*<bind>*/using var s = new S();/*</bind>*/ } } ref struct S { public void Dispose(int a = 1, bool b = true, params object[] others) { } } "; string expectedOperationTree = @" IUsingDeclarationOperation(IsAsynchronous: False, DisposeMethod: void S.Dispose([System.Int32 a = 1], [System.Boolean b = true], params System.Object[] others)) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using var s = new S();') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using var s = new S();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var s = new S()') Declarators: IVariableDeclaratorOperation (Symbol: S s) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's = new S()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new S()') IObjectCreationOperation (Constructor: S..ctor()) (OperationKind.ObjectCreation, Type: S) (Syntax: 'new S()') Arguments(0) Initializer: null Initializer: null DisposeArguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'using var s = new S();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'using var s = new S();') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: others) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'using var s = new S();') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Object[], IsImplicit) (Syntax: 'using var s = new S();') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'using var s = new S();') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'using var s = new S();') Element Values(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingDeclaration_LocalFunctionDefinedAfterUsingReferenceBeforeUsing() { var comp = CreateCompilation(@" using System; class C { void M() /*<bind>*/{ localFunc2(); static void localFunc() {} using IDisposable i = null; localFunc(); static void localFunc2() {} localFunc3(); static void localFunc3() {} }/*</bind>*/ } "); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (7 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.IDisposable i IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();') Expression: IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... alFunc() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null') Declarators: IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();') Expression: IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc2()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc2() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();') Expression: IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void localFunc3()) (OperationKind.LocalFunction, Type: null) (Syntax: 'static void ... lFunc3() {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ", DiagnosticDescription.None); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IDisposable i] Methods: [void localFunc()] [void localFunc2()] [void localFunc3()] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc2();') Expression: IInvocationOperation (void localFunc2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc();') Expression: IInvocationOperation (void localFunc()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'localFunc3();') Expression: IInvocationOperation (void localFunc3()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'localFunc3()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null') Instance Receiver: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } { void localFunc() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Exit Predecessors: [B0#0R1] Statements (0) } { void localFunc2() Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Block[B1#1R1] - Exit Predecessors: [B0#1R1] Statements (0) } { void localFunc3() Block[B0#2R1] - Entry Statements (0) Next (Regular) Block[B1#2R1] Block[B1#2R1] - Exit Predecessors: [B0#2R1] Statements (0) } } Block[B6] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void UsingDeclaration_LocalDefinedAfterUsingReferenceBeforeUsing() { var comp = CreateCompilation(@" using System; class C { void M() /*<bind>*/{ _ = local; using IDisposable i = null; object local = null; }/*</bind>*/ } "); var expectedDiagnostics = new DiagnosticDescription[] { // (8,13): error CS0841: Cannot use local variable 'local' before it is declared // _ = local; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "local").WithArguments("local").WithLocation(8, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (3 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') Locals: Local_1: System.IDisposable i Local_2: System.Object local IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local') IUsingDeclarationOperation(IsAsynchronous: False) (OperationKind.UsingDeclaration, Type: null) (Syntax: 'using IDisp ... e i = null;') DeclarationGroup: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'using IDisp ... e i = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IDisposable i = null') Declarators: IVariableDeclaratorOperation (Symbol: System.IDisposable i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'object local = null;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'object local = null') Declarators: IVariableDeclaratorOperation (Symbol: System.Object local) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'local = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Initializer: null ", expectedDiagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.IDisposable i] [System.Object local] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = local;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = local') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: local (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'local') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'local = null') Left: ILocalReferenceOperation: local (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'local = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i = null') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'i = null') Instance Receiver: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.IDisposable, IsImplicit) (Syntax: 'i = null') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void UsingDeclaration_InsideSwitchCaseEmbeddedStatements() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(int x) /*<bind>*/{ switch (x) { case 5: using C1 o1 = new C1(); break; } }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(14,17): error CS8647: A using variable cannot be used directly within a switch section (consider using braces). // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(14, 17) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [C1 o1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '5') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B4] Entering: {R3} {R4} .try {R3, R4} { Block[B4] - Block Predecessors: [B3] Statements (0) Next (Regular) Block[B8] Finalizing: {R5} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } Block[B8] - Exit Predecessors: [B2] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideIfEmbeddedStatement() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(bool b) /*<bind>*/{ if (b) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(12,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(12, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [C1 o1] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R2} {R3} .try {R2, R3} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B7] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideForEmbeddedStatement() { var source = @" using System; using System.Collections; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M() /*<bind>*/{ for (;;) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C1 o1] Block[B1] - Block Predecessors: [B0] [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B1] Entering: {R1} Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void UsingDeclaration_InsideForEachEmbeddedStatement() { var source = @" using System; using System.Collections; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void M(IEnumerable e) /*<bind>*/{ foreach (var o in e) using C1 o1 = new C1(); }/*</bind>*/ }"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // using C1 o1 = new C1(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "using C1 o1 = new C1();").WithLocation(13, 13) }; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e') Value: IInvocationOperation (virtual System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'e') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) Operand: IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'e') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B12] IInvocationOperation (virtual System.Boolean System.Collections.IEnumerator.MoveNext()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'e') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Arguments(0) Finalizing: {R9} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [System.Object o] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'var') Left: ILocalReferenceOperation: o (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'var') Right: IPropertyReferenceOperation: System.Object System.Collections.IEnumerator.Current { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'var') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { Locals: [C1 o1] Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Left: ILocalReferenceOperation: o1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Right: IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()') Arguments(0) Initializer: null Next (Regular) Block[B5] Entering: {R6} {R7} .try {R6, R7} { Block[B5] - Block Predecessors: [B4] Statements (0) Next (Regular) Block[B2] Finalizing: {R8} Leaving: {R7} {R6} {R5} {R4} } .finally {R8} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: o1 (OperationKind.LocalReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'o1 = new C1()') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } } } .finally {R9} { CaptureIds: [1] Block[B9] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ExplicitReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'e') Jump if True (Regular) to Block[B11] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'e') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B9] Statements (1) IInvocationOperation (virtual void System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'e') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'e') Arguments(0) Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B12] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/CSharp/Impl/Options/Formatting/FormattingGeneralOptionPageStrings.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.CSharp.Options { internal static class FormattingGeneralOptionPageStrings { public static string General => CSharpVSResources.General; } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Options { internal static class FormattingGeneralOptionPageStrings { public static string General => CSharpVSResources.General; } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Completion/KeywordRecommenders/RecommendationHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) End Function End Module End Namespace
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Util/WriteDumper.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. '----------------------------------------------------------------------------------------------------------- 'Code the generate a dumper class for a given parse tree. Reads the parse tree and outputs 'a dumper utility class. '----------------------------------------------------------------------------------------------------------- Imports System.IO Friend Class WriteDumper Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write the dumper utility function to the given file. Public Sub WriteDumper(filename As String) _writer = New StreamWriter(New FileStream(filename, FileMode.Create, FileAccess.Write)) Using _writer GenerateFile() End Using End Sub ' Write the whole contents of the file. Private Sub GenerateFile() _writer.WriteLine("' Definition of parse trees dumper.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub ' Create imports and the namespace declaration around the whole file Private Sub GenerateNamespace() _writer.WriteLine("Imports System.Collections.Generic") _writer.WriteLine("Imports System.IO") _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", _parseTree.NamespaceName) _writer.WriteLine() End If GenerateDumperClass() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If End Sub ' Generate the partial part of the utilities class with the DumpTree function in it. Private Sub GenerateDumperClass() _writer.WriteLine(" Public Partial Class NodeInfo") _writer.WriteLine() ' Create the nested visitor class that does all the real work. GenerateDumpVisitor() _writer.WriteLine(" End Class") End Sub Private Sub GenerateDumpVisitor() ' Write out the first boilerplate part of the visitor _writer.WriteLine(" Private Class Visitor") _writer.WriteLine(" Inherits VisualBasicSyntaxVisitor(Of NodeInfo)") _writer.WriteLine() GenerateDumpVisitorMethods() _writer.WriteLine(" End Class") End Sub ' Generate the Visitor class definition Private Sub GenerateDumpVisitorMethods() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateDumpVisitorMethod(nodeStructure) Next End Sub ' Generate a method in the Visitor class that dumps the given node type. Private Sub GenerateDumpVisitorMethod(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As NodeInfo", VisitorMethodName(nodeStructure), StructureTypeName(nodeStructure)) ' Node, and name of the node structure _writer.WriteLine(" Return New NodeInfo(") _writer.WriteLine(" ""{0}"",", StructureTypeName(nodeStructure)) ' Fields of the node structure Dim fieldList = GetAllFieldsOfStructure(nodeStructure) If fieldList.Count > 0 Then _writer.WriteLine(" { ") For i = 0 To fieldList.Count - 1 GenerateFieldInfo(fieldList(i), i = fieldList.Count - 1) Next _writer.WriteLine(" },") Else _writer.WriteLine(" Nothing,") End If ' Children (including child lists) Dim childList = GetAllChildrenOfStructure(nodeStructure) _writer.WriteLine(" { ") For i = 0 To childList.Count - 1 GenerateChildInfo(childList(i), i = childList.Count - 1) Next _writer.WriteLine(" })") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Write out the code to create info about a simple field; just a primitive Private Sub GenerateFieldInfo(field As ParseNodeField, last As Boolean) _writer.Write(" New NodeInfo.FieldInfo(""{0}"", GetType({1}), node.{0})", FieldPropertyName(field), FieldTypeRef(field)) If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub ' Write out the code to create info about a child or child list Private Sub GenerateChildInfo(child As ParseNodeChild, last As Boolean) If child.IsList Then If child.IsSeparated Then _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SeparatedNodeList, GetType({1}), node.{0}, node.{0}.Separators)", ChildPropertyName(child), BaseTypeReference(child)) Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.NodeList, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SingleNode, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- 'Code the generate a dumper class for a given parse tree. Reads the parse tree and outputs 'a dumper utility class. '----------------------------------------------------------------------------------------------------------- Imports System.IO Friend Class WriteDumper Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write the dumper utility function to the given file. Public Sub WriteDumper(filename As String) _writer = New StreamWriter(New FileStream(filename, FileMode.Create, FileAccess.Write)) Using _writer GenerateFile() End Using End Sub ' Write the whole contents of the file. Private Sub GenerateFile() _writer.WriteLine("' Definition of parse trees dumper.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub ' Create imports and the namespace declaration around the whole file Private Sub GenerateNamespace() _writer.WriteLine("Imports System.Collections.Generic") _writer.WriteLine("Imports System.IO") _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", _parseTree.NamespaceName) _writer.WriteLine() End If GenerateDumperClass() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If End Sub ' Generate the partial part of the utilities class with the DumpTree function in it. Private Sub GenerateDumperClass() _writer.WriteLine(" Public Partial Class NodeInfo") _writer.WriteLine() ' Create the nested visitor class that does all the real work. GenerateDumpVisitor() _writer.WriteLine(" End Class") End Sub Private Sub GenerateDumpVisitor() ' Write out the first boilerplate part of the visitor _writer.WriteLine(" Private Class Visitor") _writer.WriteLine(" Inherits VisualBasicSyntaxVisitor(Of NodeInfo)") _writer.WriteLine() GenerateDumpVisitorMethods() _writer.WriteLine(" End Class") End Sub ' Generate the Visitor class definition Private Sub GenerateDumpVisitorMethods() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateDumpVisitorMethod(nodeStructure) Next End Sub ' Generate a method in the Visitor class that dumps the given node type. Private Sub GenerateDumpVisitorMethod(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As NodeInfo", VisitorMethodName(nodeStructure), StructureTypeName(nodeStructure)) ' Node, and name of the node structure _writer.WriteLine(" Return New NodeInfo(") _writer.WriteLine(" ""{0}"",", StructureTypeName(nodeStructure)) ' Fields of the node structure Dim fieldList = GetAllFieldsOfStructure(nodeStructure) If fieldList.Count > 0 Then _writer.WriteLine(" { ") For i = 0 To fieldList.Count - 1 GenerateFieldInfo(fieldList(i), i = fieldList.Count - 1) Next _writer.WriteLine(" },") Else _writer.WriteLine(" Nothing,") End If ' Children (including child lists) Dim childList = GetAllChildrenOfStructure(nodeStructure) _writer.WriteLine(" { ") For i = 0 To childList.Count - 1 GenerateChildInfo(childList(i), i = childList.Count - 1) Next _writer.WriteLine(" })") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Write out the code to create info about a simple field; just a primitive Private Sub GenerateFieldInfo(field As ParseNodeField, last As Boolean) _writer.Write(" New NodeInfo.FieldInfo(""{0}"", GetType({1}), node.{0})", FieldPropertyName(field), FieldTypeRef(field)) If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub ' Write out the code to create info about a child or child list Private Sub GenerateChildInfo(child As ParseNodeChild, last As Boolean) If child.IsList Then If child.IsSeparated Then _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SeparatedNodeList, GetType({1}), node.{0}, node.{0}.Separators)", ChildPropertyName(child), BaseTypeReference(child)) Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.NodeList, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SingleNode, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub End Class
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.AddRequiredParentheses), Shared] internal class AddRequiredParenthesesCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AddRequiredParenthesesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var firstDiagnostic = context.Diagnostics[0]; context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, firstDiagnostic, c), firstDiagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey]), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var location = diagnostic.AdditionalLocations[0]; var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken); // Do not add the simplifier annotation. We do not want the simplifier undoing the // work we just did. editor.ReplaceNode(node, (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(AnalyzersResources.Add_parentheses_for_clarity, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.AddRequiredParentheses), Shared] internal class AddRequiredParenthesesCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AddRequiredParenthesesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var firstDiagnostic = context.Diagnostics[0]; context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, firstDiagnostic, c), firstDiagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey]), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var location = diagnostic.AdditionalLocations[0]; var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken); // Do not add the simplifier annotation. We do not want the simplifier undoing the // work we just did. editor.ReplaceNode(node, (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(AnalyzersResources.Add_parentheses_for_clarity, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/SolutionExplorer/DiagnosticItem/CpsUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal static class CpsUtilities { /// <summary> /// Given the canonical name of a node representing an analyzer assembly in the /// CPS-based project system extracts out the full path to the assembly. /// </summary> /// <param name="projectDirectoryPath">The full path to the project directory</param> /// <param name="analyzerNodeCanonicalName">The canonical name of the analyzer node in the hierarchy</param> /// <returns>The full path to the analyzer assembly on disk, or null if <paramref name="analyzerNodeCanonicalName"/> /// cannot be parsed.</returns> /// <remarks> /// The canonical name takes the following form: /// /// [{path to project directory}\]{target framework}\analyzerdependency\{path to assembly} /// /// e.g.: /// /// C:\projects\solutions\MyProj\netstandard2.0\analyzerdependency\C:\users\me\.packages\somePackage\lib\someAnalyzer.dll /// /// This method exists solely to extract out the "path to assembly" part, i.e. /// "C:\users\me\.packages\somePackage\lib\someAnalyzer.dll". We don't need the /// other parts. /// /// Note that the path to the project directory is optional. /// </remarks> public static string? ExtractAnalyzerFilePath(string projectDirectoryPath, string analyzerNodeCanonicalName) { // The canonical name may or may not start with the path to the project's directory. if (!projectDirectoryPath.EndsWith("\\")) { projectDirectoryPath += '\\'; } if (analyzerNodeCanonicalName.StartsWith(projectDirectoryPath, StringComparison.OrdinalIgnoreCase)) { // Extract the rest of the string analyzerNodeCanonicalName = analyzerNodeCanonicalName.Substring(projectDirectoryPath.Length); } // Find the slash after the target framework var backslashIndex = analyzerNodeCanonicalName.IndexOf('\\'); if (backslashIndex < 0) { return null; } // If the path does not contain "analyzerdependency\" immediately after the first slash, it // is a newer form of the analyzer tree item's file path (VS16.7) which requires no processing. // // It is theoretically possible that this incorrectly identifies an analyzer assembly // defined under "c:\analyzerdependency\..." as data in the old format, however this is very // unlikely. The side effect of such a problem is that analyzer's diagnostics would not // populate in the tree. if (analyzerNodeCanonicalName.IndexOf(@"analyzerdependency\", backslashIndex + 1, @"analyzerdependency\".Length, StringComparison.OrdinalIgnoreCase) != backslashIndex + 1) { return analyzerNodeCanonicalName; } // Find the slash after "analyzerdependency" backslashIndex = analyzerNodeCanonicalName.IndexOf('\\', backslashIndex + 1); if (backslashIndex < 0) { return null; } // The rest of the string is the path. return analyzerNodeCanonicalName.Substring(backslashIndex + 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal static class CpsUtilities { /// <summary> /// Given the canonical name of a node representing an analyzer assembly in the /// CPS-based project system extracts out the full path to the assembly. /// </summary> /// <param name="projectDirectoryPath">The full path to the project directory</param> /// <param name="analyzerNodeCanonicalName">The canonical name of the analyzer node in the hierarchy</param> /// <returns>The full path to the analyzer assembly on disk, or null if <paramref name="analyzerNodeCanonicalName"/> /// cannot be parsed.</returns> /// <remarks> /// The canonical name takes the following form: /// /// [{path to project directory}\]{target framework}\analyzerdependency\{path to assembly} /// /// e.g.: /// /// C:\projects\solutions\MyProj\netstandard2.0\analyzerdependency\C:\users\me\.packages\somePackage\lib\someAnalyzer.dll /// /// This method exists solely to extract out the "path to assembly" part, i.e. /// "C:\users\me\.packages\somePackage\lib\someAnalyzer.dll". We don't need the /// other parts. /// /// Note that the path to the project directory is optional. /// </remarks> public static string? ExtractAnalyzerFilePath(string projectDirectoryPath, string analyzerNodeCanonicalName) { // The canonical name may or may not start with the path to the project's directory. if (!projectDirectoryPath.EndsWith("\\")) { projectDirectoryPath += '\\'; } if (analyzerNodeCanonicalName.StartsWith(projectDirectoryPath, StringComparison.OrdinalIgnoreCase)) { // Extract the rest of the string analyzerNodeCanonicalName = analyzerNodeCanonicalName.Substring(projectDirectoryPath.Length); } // Find the slash after the target framework var backslashIndex = analyzerNodeCanonicalName.IndexOf('\\'); if (backslashIndex < 0) { return null; } // If the path does not contain "analyzerdependency\" immediately after the first slash, it // is a newer form of the analyzer tree item's file path (VS16.7) which requires no processing. // // It is theoretically possible that this incorrectly identifies an analyzer assembly // defined under "c:\analyzerdependency\..." as data in the old format, however this is very // unlikely. The side effect of such a problem is that analyzer's diagnostics would not // populate in the tree. if (analyzerNodeCanonicalName.IndexOf(@"analyzerdependency\", backslashIndex + 1, @"analyzerdependency\".Length, StringComparison.OrdinalIgnoreCase) != backslashIndex + 1) { return analyzerNodeCanonicalName; } // Find the slash after "analyzerdependency" backslashIndex = analyzerNodeCanonicalName.IndexOf('\\', backslashIndex + 1); if (backslashIndex < 0) { return null; } // The rest of the string is the path. return analyzerNodeCanonicalName.Substring(backslashIndex + 1); } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Syntax/CSharpSyntaxTree.Dummy.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.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { internal sealed class DummySyntaxTree : CSharpSyntaxTree { private readonly CompilationUnitSyntax _node; public DummySyntaxTree() { _node = this.CloneNodeAsRoot(SyntaxFactory.ParseCompilationUnit(string.Empty)); } public override string ToString() { return string.Empty; } public override SourceText GetText(CancellationToken cancellationToken) { return SourceText.From(string.Empty, Encoding.UTF8); } public override bool TryGetText(out SourceText text) { text = SourceText.From(string.Empty, Encoding.UTF8); return true; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override int Length { get { return 0; } } public override CSharpParseOptions Options { get { return CSharpParseOptions.Default; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => throw ExceptionUtilities.Unreachable; public override string FilePath { get { return string.Empty; } } public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _node; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _node; return true; } public override bool HasCompilationUnitRoot { get { return true; } } public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { return default(FileLinePositionSpan); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { return SyntaxFactory.SyntaxTree(root, options: options, path: FilePath, encoding: null); } public override SyntaxTree WithFilePath(string path) { return SyntaxFactory.SyntaxTree(_node, options: this.Options, path: path, encoding: 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.Collections.Immutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { internal sealed class DummySyntaxTree : CSharpSyntaxTree { private readonly CompilationUnitSyntax _node; public DummySyntaxTree() { _node = this.CloneNodeAsRoot(SyntaxFactory.ParseCompilationUnit(string.Empty)); } public override string ToString() { return string.Empty; } public override SourceText GetText(CancellationToken cancellationToken) { return SourceText.From(string.Empty, Encoding.UTF8); } public override bool TryGetText(out SourceText text) { text = SourceText.From(string.Empty, Encoding.UTF8); return true; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override int Length { get { return 0; } } public override CSharpParseOptions Options { get { return CSharpParseOptions.Default; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => throw ExceptionUtilities.Unreachable; public override string FilePath { get { return string.Empty; } } public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _node; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _node; return true; } public override bool HasCompilationUnitRoot { get { return true; } } public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { return default(FileLinePositionSpan); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { return SyntaxFactory.SyntaxTree(root, options: options, path: FilePath, encoding: null); } public override SyntaxTree WithFilePath(string path) { return SyntaxFactory.SyntaxTree(_node, options: this.Options, path: path, encoding: null); } } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(KeywordHighlightTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag> { private readonly IHighlightingService _highlightingService; private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>()); // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HighlighterViewTaggerProvider( IThreadingContext threadingContext, IHighlightingService highlightingService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting)) { _highlightingService = highlightingService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var cancellationToken = context.CancellationToken; var document = documentSnapshotSpan.Document; // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project. // Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause // us to end up in this situation. // Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in // workspace is completed to eliminate the root cause. if (document?.SupportsSyntaxTree != true) { return; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting)) { return; } if (!caretPosition.HasValue) { return; } var snapshotSpan = documentSnapshotSpan.SnapshotSpan; var position = caretPosition.Value; var snapshot = snapshotSpan.Snapshot; // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position)); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return; } using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken)) using (s_listPool.GetPooledObject(out var highlights)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); _highlightingService.AddHighlights(root, position, highlights, cancellationToken); foreach (var span in highlights) { context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance)); } } } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(KeywordHighlightTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag> { private readonly IHighlightingService _highlightingService; private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>()); // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HighlighterViewTaggerProvider( IThreadingContext threadingContext, IHighlightingService highlightingService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting)) { _highlightingService = highlightingService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var cancellationToken = context.CancellationToken; var document = documentSnapshotSpan.Document; // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project. // Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause // us to end up in this situation. // Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in // workspace is completed to eliminate the root cause. if (document?.SupportsSyntaxTree != true) { return; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting)) { return; } if (!caretPosition.HasValue) { return; } var snapshotSpan = documentSnapshotSpan.SnapshotSpan; var position = caretPosition.Value; var snapshot = snapshotSpan.Snapshot; // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position)); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return; } using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken)) using (s_listPool.GetPooledObject(out var highlights)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); _highlightingService.AddHighlights(root, position, highlights, cancellationToken); foreach (var span in highlights) { context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance)); } } } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/ExternalAccess/UnitTesting/Api/UnitTestingRemoteServiceConnectionWrapper.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal readonly struct UnitTestingRemoteServiceConnectionWrapper : IDisposable { internal RemoteServiceConnection UnderlyingObject { get; } internal UnitTestingRemoteServiceConnectionWrapper(RemoteServiceConnection underlyingObject) => UnderlyingObject = underlyingObject; public bool IsDefault => UnderlyingObject == null; public async Task<bool> TryRunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { await UnderlyingObject.RunRemoteAsync(targetName, solution, arguments, cancellationToken).ConfigureAwait(false); return true; } public async Task<Optional<T>> TryRunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => await UnderlyingObject.RunRemoteAsync<T>(targetName, solution, arguments, cancellationToken).ConfigureAwait(false); public void Dispose() => UnderlyingObject?.Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal readonly struct UnitTestingRemoteServiceConnectionWrapper : IDisposable { internal RemoteServiceConnection UnderlyingObject { get; } internal UnitTestingRemoteServiceConnectionWrapper(RemoteServiceConnection underlyingObject) => UnderlyingObject = underlyingObject; public bool IsDefault => UnderlyingObject == null; public async Task<bool> TryRunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { await UnderlyingObject.RunRemoteAsync(targetName, solution, arguments, cancellationToken).ConfigureAwait(false); return true; } public async Task<Optional<T>> TryRunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => await UnderlyingObject.RunRemoteAsync<T>(targetName, solution, arguments, cancellationToken).ConfigureAwait(false); public void Dispose() => UnderlyingObject?.Dispose(); } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/Symbols/Retargeting/RetargetExplicitInterfaceImplementation.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RetargetExplicitInterfaceImplementation : CSharpTestBase { [Fact] public void ExplicitInterfaceImplementationRetargeting() { var comp1 = CreateCompilation( new AssemblyIdentity("Assembly1"), new string[] { @" public class C : Interface1 { void Interface1.Method1() { } void Interface1.Method2() { } void Interface1.Method3(bool b) { } void Interface1.Method4(Class1 c) { } string Interface1.Property1 { get; set; } string Interface1.Property2 { get; set; } string Interface1.Property3 { get; set; } Class1 Interface1.Property4 { get; set; } string Interface1.this[string x] { get { return null; } set { } } string Interface1.this[string x, string y] { get { return null; } set { } } string Interface1.this[string x, string y, string z] { get { return null; } set { } } Class1 Interface1.this[Class1 x, Class1 y, Class1 z, Class1 w] { get { return null; } set { } } event System.Action Interface1.Event1 { add { } remove { } } event System.Action Interface1.Event2 { add { } remove { } } event System.Action Interface1.Event3 { add { } remove { } } event Delegate1 Interface1.Event4 { add { } remove { } } } " }, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, }); comp1.VerifyDiagnostics(); var globalNamespace1 = comp1.GlobalNamespace; var classC = globalNamespace1.GetTypeMembers("C").Single(); var interfaceV1 = globalNamespace1.GetTypeMembers("Interface1").Single(); var interfaceV1Method1 = (MethodSymbol)interfaceV1.GetMembers("Method1").Single(); var interfaceV1Method2 = (MethodSymbol)interfaceV1.GetMembers("Method2").Single(); var interfaceV1Method3 = (MethodSymbol)interfaceV1.GetMembers("Method3").Single(); var interfaceV1Method4 = (MethodSymbol)interfaceV1.GetMembers("Method4").Single(); var interfaceV1Property1 = (PropertySymbol)interfaceV1.GetMembers("Property1").Single(); var interfaceV1Property2 = (PropertySymbol)interfaceV1.GetMembers("Property2").Single(); var interfaceV1Property3 = (PropertySymbol)interfaceV1.GetMembers("Property3").Single(); var interfaceV1Property4 = (PropertySymbol)interfaceV1.GetMembers("Property4").Single(); var interfaceV1Indexer1 = FindIndexerWithParameterCount(interfaceV1, 1); var interfaceV1Indexer2 = FindIndexerWithParameterCount(interfaceV1, 2); var interfaceV1Indexer3 = FindIndexerWithParameterCount(interfaceV1, 3); var interfaceV1Indexer4 = FindIndexerWithParameterCount(interfaceV1, 4); var interfaceV1Event1 = (EventSymbol)interfaceV1.GetMembers("Event1").Single(); var interfaceV1Event2 = (EventSymbol)interfaceV1.GetMembers("Event2").Single(); var interfaceV1Event3 = (EventSymbol)interfaceV1.GetMembers("Event3").Single(); var interfaceV1Event4 = (EventSymbol)interfaceV1.GetMembers("Event4").Single(); foreach (var member in classC.GetMembers()) { switch (member.Kind) { case SymbolKind.Method: var method = (MethodSymbol)member; if (method.MethodKind == MethodKind.ExplicitInterfaceImplementation) { Assert.Equal(interfaceV1, method.ExplicitInterfaceImplementations.Single().ContainingType); } break; case SymbolKind.Property: Assert.Equal(interfaceV1, ((PropertySymbol)member).ExplicitInterfaceImplementations.Single().ContainingType); break; case SymbolKind.Event: Assert.Equal(interfaceV1, ((EventSymbol)member).ExplicitInterfaceImplementations.Single().ContainingType); break; case SymbolKind.ErrorType: Assert.True(false); break; } } var comp2 = CreateCompilation( new AssemblyIdentity("Assembly2"), new string[] {@" public class D : C { } " }, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(comp1) }); Assert.False(comp2.GetDiagnostics().Any()); var globalNamespace2 = comp2.GlobalNamespace; var interfaceV2 = globalNamespace2.GetTypeMembers("Interface1").Single(); Assert.NotSame(interfaceV1, interfaceV2); var interfaceV2Method1 = (MethodSymbol)interfaceV2.GetMembers("Method1").Single(); //Method2 deleted var interfaceV2Method3 = (MethodSymbol)interfaceV2.GetMembers("Method3").Single(); var interfaceV2Method4 = (MethodSymbol)interfaceV2.GetMembers("Method4").Single(); var interfaceV2Property1 = (PropertySymbol)interfaceV2.GetMembers("Property1").Single(); //Property2 deleted var interfaceV2Property3 = (PropertySymbol)interfaceV2.GetMembers("Property3").Single(); var interfaceV2Property4 = (PropertySymbol)interfaceV2.GetMembers("Property4").Single(); var interfaceV2Indexer1 = FindIndexerWithParameterCount(interfaceV2, 1); //Two-parameter indexer deleted var interfaceV2Indexer3 = FindIndexerWithParameterCount(interfaceV2, 3); var interfaceV2Indexer4 = FindIndexerWithParameterCount(interfaceV2, 4); var interfaceV2Event1 = (EventSymbol)interfaceV2.GetMembers("Event1").Single(); //Event2 deleted var interfaceV2Event3 = (EventSymbol)interfaceV2.GetMembers("Event3").Single(); var interfaceV2Event4 = (EventSymbol)interfaceV2.GetMembers("Event4").Single(); var classD = globalNamespace2.GetTypeMembers("D").Single(); var retargetedClassC = classD.BaseType(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetedClassC); Assert.Equal(interfaceV2, retargetedClassC.Interfaces().Single()); var retargetedClassCMethod1 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method1").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod1); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod1.MethodKind); var retargetedClassCMethod1Impl = retargetedClassCMethod1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassCMethod1Impl); Assert.NotSame(interfaceV1Method1, retargetedClassCMethod1Impl); Assert.Equal(retargetedClassCMethod1Impl.ToTestDisplayString(), interfaceV1Method1.ToTestDisplayString()); } var retargetedClassCMethod2 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method2").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod2); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod2.MethodKind); //since the method is missing from V2 of the interface Assert.False(retargetedClassCMethod2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCMethod3 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method3").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod3); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod3.MethodKind); //since the method has a different signature in V2 of the interface Assert.False(retargetedClassCMethod3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCMethod4 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method4").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod4); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod4.MethodKind); var retargetedClassCMethod4Impl = retargetedClassCMethod4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method4, retargetedClassCMethod4Impl); Assert.NotSame(interfaceV1Method4, retargetedClassCMethod4Impl); Assert.Equal(retargetedClassCMethod4Impl.ToTestDisplayString(), interfaceV1Method4.ToTestDisplayString()); } var retargetedClassCProperty1 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property1").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty1); var retargetedClassCProperty1Impl = retargetedClassCProperty1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassCProperty1Impl); Assert.NotSame(interfaceV1Property1, retargetedClassCProperty1Impl); Assert.Equal(retargetedClassCProperty1Impl.Name, interfaceV1Property1.Name); Assert.Equal(retargetedClassCProperty1Impl.Type.ToTestDisplayString(), interfaceV1Property1.Type.ToTestDisplayString()); } var retargetedClassCProperty2 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property2").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty2); //since the property is missing from V2 of the interface Assert.False(retargetedClassCProperty2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCProperty3 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property3").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty3); //since the property has a different type in V2 of the interface Assert.False(retargetedClassCProperty3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCProperty4 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property4").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty4); var retargetedClassCProperty4Impl = retargetedClassCProperty4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property4, retargetedClassCProperty4Impl); Assert.NotSame(interfaceV1Property4, retargetedClassCProperty4Impl); Assert.Equal(retargetedClassCProperty4Impl.Name, interfaceV1Property4.Name); Assert.Equal(retargetedClassCProperty4Impl.Type.ToTestDisplayString(), interfaceV1Property4.Type.ToTestDisplayString()); } var retargetedClassCIndexer1 = FindIndexerWithParameterCount(retargetedClassC, 1); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer1); var retargetedClassCIndexer1Impl = retargetedClassCIndexer1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Indexer1, retargetedClassCIndexer1Impl); Assert.NotSame(interfaceV1Indexer1, retargetedClassCIndexer1Impl); Assert.Equal(retargetedClassCIndexer1Impl.Name, interfaceV1Indexer1.Name); Assert.Equal(retargetedClassCIndexer1Impl.Type.ToTestDisplayString(), interfaceV1Indexer1.Type.ToTestDisplayString()); } var retargetedClassCIndexer2 = FindIndexerWithParameterCount(retargetedClassC, 2); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer2); //since the property is missing from V2 of the interface Assert.False(retargetedClassCIndexer2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCIndexer3 = FindIndexerWithParameterCount(retargetedClassC, 3); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer3); //since the property has a different type in V2 of the interface Assert.False(retargetedClassCIndexer3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCIndexer4 = FindIndexerWithParameterCount(retargetedClassC, 4); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer4); var retargetedClassCIndexer4Impl = retargetedClassCIndexer4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Indexer4, retargetedClassCIndexer4Impl); Assert.NotSame(interfaceV1Indexer4, retargetedClassCIndexer4Impl); Assert.Equal(retargetedClassCIndexer4Impl.Name, interfaceV1Indexer4.Name); Assert.Equal(retargetedClassCIndexer4Impl.Type.ToTestDisplayString(), interfaceV1Indexer4.Type.ToTestDisplayString()); } var retargetedClassCEvent1 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event1").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent1); var retargetedClassCEvent1Impl = retargetedClassCEvent1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassCEvent1Impl); Assert.NotSame(interfaceV1Event1, retargetedClassCEvent1Impl); Assert.Equal(retargetedClassCEvent1Impl.Name, interfaceV1Event1.Name); Assert.Equal(retargetedClassCEvent1Impl.Type.ToTestDisplayString(), interfaceV1Event1.Type.ToTestDisplayString()); } var retargetedClassCEvent2 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event2").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent2); //since the event is missing from V2 of the interface Assert.False(retargetedClassCEvent2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCEvent3 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event3").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent3); //since the event has a different type in V2 of the interface Assert.False(retargetedClassCEvent3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCEvent4 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event4").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent4); var retargetedClassCEvent4Impl = retargetedClassCEvent4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event4, retargetedClassCEvent4Impl); Assert.NotSame(interfaceV1Event4, retargetedClassCEvent4Impl); Assert.Equal(retargetedClassCEvent4Impl.Name, interfaceV1Event4.Name); Assert.Equal(retargetedClassCEvent4Impl.Type.ToTestDisplayString(), interfaceV1Event4.Type.ToTestDisplayString()); } } private static PropertySymbol FindIndexerWithParameterCount(NamedTypeSymbol type, int parameterCount) { return type.GetMembers().Where(s => s.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single(p => p.Parameters.Length == parameterCount); } [Fact] public void ExplicitInterfaceImplementationRetargetingGeneric() { var comp1 = CreateCompilation( new AssemblyIdentity("Assembly1"), new string[] { @" public class C1<S> : Interface2<S> { void Interface2<S>.Method1(S s) { } S Interface2<S>.Property1 { get; set; } event System.Action<S> Interface2<S>.Event1 { add { } remove { } } } public class C2 : Interface2<int> { void Interface2<int>.Method1(int i) { } int Interface2<int>.Property1 { get; set; } event System.Action<int> Interface2<int>.Event1 { add { } remove { } } } public class C3 : Interface2<Class1> { void Interface2<Class1>.Method1(Class1 c) { } Class1 Interface2<Class1>.Property1 { get; set; } event System.Action<Class1> Interface2<Class1>.Event1 { add { } remove { } } } " }, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, }); var d = comp1.GetDiagnostics(); Assert.False(comp1.GetDiagnostics().Any()); var globalNamespace1 = comp1.GlobalNamespace; var classC1 = globalNamespace1.GetTypeMembers("C1").Single(); var classC2 = globalNamespace1.GetTypeMembers("C2").Single(); var classC3 = globalNamespace1.GetTypeMembers("C3").Single(); foreach (var diag in comp1.GetDiagnostics()) { Console.WriteLine(diag); } var comp2 = CreateCompilation( new AssemblyIdentity("Assembly2"), new string[] {@" public class D1<R> : C1<R> { } public class D2 : C2 { } public class D3 : C3 { } " }, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(comp1) }); Assert.False(comp2.GetDiagnostics().Any()); var globalNamespace2 = comp2.GlobalNamespace; var interfaceV2 = globalNamespace2.GetTypeMembers("Interface2").Single(); var interfaceV2Method1 = interfaceV2.GetMembers("Method1").Single(); var interfaceV2Property1 = interfaceV2.GetMembers("Property1").Single(); var interfaceV2Event1 = interfaceV2.GetMembers("Event1").Single(); var classD1 = globalNamespace2.GetTypeMembers("D1").Single(); var classD2 = globalNamespace2.GetTypeMembers("D2").Single(); var classD3 = globalNamespace2.GetTypeMembers("D3").Single(); var retargetedClassC1 = classD1.BaseType(); var retargetedClassC2 = classD2.BaseType(); var retargetedClassC3 = classD3.BaseType(); var retargetedClassC1Method1 = (MethodSymbol)retargetedClassC1.GetMembers("Interface2<S>.Method1").Single(); var retargetedClassC1Method1Impl = retargetedClassC1Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC1Method1Impl.OriginalDefinition); var retargetedClassC2Method1 = (MethodSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Method1").Single(); var retargetedClassC2Method1Impl = retargetedClassC2Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC2Method1Impl.OriginalDefinition); var retargetedClassC3Method1 = (MethodSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Method1").Single(); var retargetedClassC3Method1Impl = retargetedClassC3Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC3Method1Impl.OriginalDefinition); var retargetedClassC1Property1 = (PropertySymbol)retargetedClassC1.GetMembers("Interface2<S>.Property1").Single(); var retargetedClassC1Property1Impl = retargetedClassC1Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC1Property1Impl.OriginalDefinition); var retargetedClassC2Property1 = (PropertySymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Property1").Single(); var retargetedClassC2Property1Impl = retargetedClassC2Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC2Property1Impl.OriginalDefinition); var retargetedClassC3Property1 = (PropertySymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Property1").Single(); var retargetedClassC3Property1Impl = retargetedClassC3Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC3Property1Impl.OriginalDefinition); var retargetedClassC1Event1 = (EventSymbol)retargetedClassC1.GetMembers("Interface2<S>.Event1").Single(); var retargetedClassC1Event1Impl = retargetedClassC1Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC1Event1Impl.OriginalDefinition); var retargetedClassC2Event1 = (EventSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Event1").Single(); var retargetedClassC2Event1Impl = retargetedClassC2Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC2Event1Impl.OriginalDefinition); var retargetedClassC3Event1 = (EventSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Event1").Single(); var retargetedClassC3Event1Impl = retargetedClassC3Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC3Event1Impl.OriginalDefinition); } [Fact] public void ExplicitInterfaceImplementationRetargetingGenericType() { var source1 = @" public class C1<T> { public interface I1 { void M(T x); } } "; var ref1 = CreateEmptyCompilation("").ToMetadataReference(); var compilation1 = CreateCompilation(source1, references: new[] { ref1 }); var source2 = @" public class C2<U> : C1<U>.I1 { void C1<U>.I1.M(U x) {} } "; var compilation2 = CreateCompilation(source2, references: new[] { compilation1.ToMetadataReference(), ref1, CreateEmptyCompilation("").ToMetadataReference() }); var compilation3 = CreateCompilation("", references: new[] { compilation1.ToMetadataReference(), compilation2.ToMetadataReference() }); Assert.NotSame(compilation2.GetTypeByMetadataName("C1`1"), compilation3.GetTypeByMetadataName("C1`1")); var c2 = compilation3.GetTypeByMetadataName("C2`1"); Assert.IsType<RetargetingNamedTypeSymbol>(c2); var m = c2.GetMethod("C1<U>.I1.M"); Assert.Equal(c2.Interfaces().Single().GetMethod("M"), m.ExplicitInterfaceImplementations.Single()); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RetargetExplicitInterfaceImplementation : CSharpTestBase { [Fact] public void ExplicitInterfaceImplementationRetargeting() { var comp1 = CreateCompilation( new AssemblyIdentity("Assembly1"), new string[] { @" public class C : Interface1 { void Interface1.Method1() { } void Interface1.Method2() { } void Interface1.Method3(bool b) { } void Interface1.Method4(Class1 c) { } string Interface1.Property1 { get; set; } string Interface1.Property2 { get; set; } string Interface1.Property3 { get; set; } Class1 Interface1.Property4 { get; set; } string Interface1.this[string x] { get { return null; } set { } } string Interface1.this[string x, string y] { get { return null; } set { } } string Interface1.this[string x, string y, string z] { get { return null; } set { } } Class1 Interface1.this[Class1 x, Class1 y, Class1 z, Class1 w] { get { return null; } set { } } event System.Action Interface1.Event1 { add { } remove { } } event System.Action Interface1.Event2 { add { } remove { } } event System.Action Interface1.Event3 { add { } remove { } } event Delegate1 Interface1.Event4 { add { } remove { } } } " }, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, }); comp1.VerifyDiagnostics(); var globalNamespace1 = comp1.GlobalNamespace; var classC = globalNamespace1.GetTypeMembers("C").Single(); var interfaceV1 = globalNamespace1.GetTypeMembers("Interface1").Single(); var interfaceV1Method1 = (MethodSymbol)interfaceV1.GetMembers("Method1").Single(); var interfaceV1Method2 = (MethodSymbol)interfaceV1.GetMembers("Method2").Single(); var interfaceV1Method3 = (MethodSymbol)interfaceV1.GetMembers("Method3").Single(); var interfaceV1Method4 = (MethodSymbol)interfaceV1.GetMembers("Method4").Single(); var interfaceV1Property1 = (PropertySymbol)interfaceV1.GetMembers("Property1").Single(); var interfaceV1Property2 = (PropertySymbol)interfaceV1.GetMembers("Property2").Single(); var interfaceV1Property3 = (PropertySymbol)interfaceV1.GetMembers("Property3").Single(); var interfaceV1Property4 = (PropertySymbol)interfaceV1.GetMembers("Property4").Single(); var interfaceV1Indexer1 = FindIndexerWithParameterCount(interfaceV1, 1); var interfaceV1Indexer2 = FindIndexerWithParameterCount(interfaceV1, 2); var interfaceV1Indexer3 = FindIndexerWithParameterCount(interfaceV1, 3); var interfaceV1Indexer4 = FindIndexerWithParameterCount(interfaceV1, 4); var interfaceV1Event1 = (EventSymbol)interfaceV1.GetMembers("Event1").Single(); var interfaceV1Event2 = (EventSymbol)interfaceV1.GetMembers("Event2").Single(); var interfaceV1Event3 = (EventSymbol)interfaceV1.GetMembers("Event3").Single(); var interfaceV1Event4 = (EventSymbol)interfaceV1.GetMembers("Event4").Single(); foreach (var member in classC.GetMembers()) { switch (member.Kind) { case SymbolKind.Method: var method = (MethodSymbol)member; if (method.MethodKind == MethodKind.ExplicitInterfaceImplementation) { Assert.Equal(interfaceV1, method.ExplicitInterfaceImplementations.Single().ContainingType); } break; case SymbolKind.Property: Assert.Equal(interfaceV1, ((PropertySymbol)member).ExplicitInterfaceImplementations.Single().ContainingType); break; case SymbolKind.Event: Assert.Equal(interfaceV1, ((EventSymbol)member).ExplicitInterfaceImplementations.Single().ContainingType); break; case SymbolKind.ErrorType: Assert.True(false); break; } } var comp2 = CreateCompilation( new AssemblyIdentity("Assembly2"), new string[] {@" public class D : C { } " }, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(comp1) }); Assert.False(comp2.GetDiagnostics().Any()); var globalNamespace2 = comp2.GlobalNamespace; var interfaceV2 = globalNamespace2.GetTypeMembers("Interface1").Single(); Assert.NotSame(interfaceV1, interfaceV2); var interfaceV2Method1 = (MethodSymbol)interfaceV2.GetMembers("Method1").Single(); //Method2 deleted var interfaceV2Method3 = (MethodSymbol)interfaceV2.GetMembers("Method3").Single(); var interfaceV2Method4 = (MethodSymbol)interfaceV2.GetMembers("Method4").Single(); var interfaceV2Property1 = (PropertySymbol)interfaceV2.GetMembers("Property1").Single(); //Property2 deleted var interfaceV2Property3 = (PropertySymbol)interfaceV2.GetMembers("Property3").Single(); var interfaceV2Property4 = (PropertySymbol)interfaceV2.GetMembers("Property4").Single(); var interfaceV2Indexer1 = FindIndexerWithParameterCount(interfaceV2, 1); //Two-parameter indexer deleted var interfaceV2Indexer3 = FindIndexerWithParameterCount(interfaceV2, 3); var interfaceV2Indexer4 = FindIndexerWithParameterCount(interfaceV2, 4); var interfaceV2Event1 = (EventSymbol)interfaceV2.GetMembers("Event1").Single(); //Event2 deleted var interfaceV2Event3 = (EventSymbol)interfaceV2.GetMembers("Event3").Single(); var interfaceV2Event4 = (EventSymbol)interfaceV2.GetMembers("Event4").Single(); var classD = globalNamespace2.GetTypeMembers("D").Single(); var retargetedClassC = classD.BaseType(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetedClassC); Assert.Equal(interfaceV2, retargetedClassC.Interfaces().Single()); var retargetedClassCMethod1 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method1").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod1); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod1.MethodKind); var retargetedClassCMethod1Impl = retargetedClassCMethod1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassCMethod1Impl); Assert.NotSame(interfaceV1Method1, retargetedClassCMethod1Impl); Assert.Equal(retargetedClassCMethod1Impl.ToTestDisplayString(), interfaceV1Method1.ToTestDisplayString()); } var retargetedClassCMethod2 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method2").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod2); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod2.MethodKind); //since the method is missing from V2 of the interface Assert.False(retargetedClassCMethod2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCMethod3 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method3").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod3); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod3.MethodKind); //since the method has a different signature in V2 of the interface Assert.False(retargetedClassCMethod3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCMethod4 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method4").Single(); { Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod4); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod4.MethodKind); var retargetedClassCMethod4Impl = retargetedClassCMethod4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method4, retargetedClassCMethod4Impl); Assert.NotSame(interfaceV1Method4, retargetedClassCMethod4Impl); Assert.Equal(retargetedClassCMethod4Impl.ToTestDisplayString(), interfaceV1Method4.ToTestDisplayString()); } var retargetedClassCProperty1 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property1").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty1); var retargetedClassCProperty1Impl = retargetedClassCProperty1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassCProperty1Impl); Assert.NotSame(interfaceV1Property1, retargetedClassCProperty1Impl); Assert.Equal(retargetedClassCProperty1Impl.Name, interfaceV1Property1.Name); Assert.Equal(retargetedClassCProperty1Impl.Type.ToTestDisplayString(), interfaceV1Property1.Type.ToTestDisplayString()); } var retargetedClassCProperty2 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property2").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty2); //since the property is missing from V2 of the interface Assert.False(retargetedClassCProperty2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCProperty3 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property3").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty3); //since the property has a different type in V2 of the interface Assert.False(retargetedClassCProperty3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCProperty4 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property4").Single(); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty4); var retargetedClassCProperty4Impl = retargetedClassCProperty4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property4, retargetedClassCProperty4Impl); Assert.NotSame(interfaceV1Property4, retargetedClassCProperty4Impl); Assert.Equal(retargetedClassCProperty4Impl.Name, interfaceV1Property4.Name); Assert.Equal(retargetedClassCProperty4Impl.Type.ToTestDisplayString(), interfaceV1Property4.Type.ToTestDisplayString()); } var retargetedClassCIndexer1 = FindIndexerWithParameterCount(retargetedClassC, 1); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer1); var retargetedClassCIndexer1Impl = retargetedClassCIndexer1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Indexer1, retargetedClassCIndexer1Impl); Assert.NotSame(interfaceV1Indexer1, retargetedClassCIndexer1Impl); Assert.Equal(retargetedClassCIndexer1Impl.Name, interfaceV1Indexer1.Name); Assert.Equal(retargetedClassCIndexer1Impl.Type.ToTestDisplayString(), interfaceV1Indexer1.Type.ToTestDisplayString()); } var retargetedClassCIndexer2 = FindIndexerWithParameterCount(retargetedClassC, 2); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer2); //since the property is missing from V2 of the interface Assert.False(retargetedClassCIndexer2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCIndexer3 = FindIndexerWithParameterCount(retargetedClassC, 3); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer3); //since the property has a different type in V2 of the interface Assert.False(retargetedClassCIndexer3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCIndexer4 = FindIndexerWithParameterCount(retargetedClassC, 4); { Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer4); var retargetedClassCIndexer4Impl = retargetedClassCIndexer4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Indexer4, retargetedClassCIndexer4Impl); Assert.NotSame(interfaceV1Indexer4, retargetedClassCIndexer4Impl); Assert.Equal(retargetedClassCIndexer4Impl.Name, interfaceV1Indexer4.Name); Assert.Equal(retargetedClassCIndexer4Impl.Type.ToTestDisplayString(), interfaceV1Indexer4.Type.ToTestDisplayString()); } var retargetedClassCEvent1 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event1").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent1); var retargetedClassCEvent1Impl = retargetedClassCEvent1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassCEvent1Impl); Assert.NotSame(interfaceV1Event1, retargetedClassCEvent1Impl); Assert.Equal(retargetedClassCEvent1Impl.Name, interfaceV1Event1.Name); Assert.Equal(retargetedClassCEvent1Impl.Type.ToTestDisplayString(), interfaceV1Event1.Type.ToTestDisplayString()); } var retargetedClassCEvent2 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event2").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent2); //since the event is missing from V2 of the interface Assert.False(retargetedClassCEvent2.ExplicitInterfaceImplementations.Any()); } var retargetedClassCEvent3 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event3").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent3); //since the event has a different type in V2 of the interface Assert.False(retargetedClassCEvent3.ExplicitInterfaceImplementations.Any()); } var retargetedClassCEvent4 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event4").Single(); { Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent4); var retargetedClassCEvent4Impl = retargetedClassCEvent4.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event4, retargetedClassCEvent4Impl); Assert.NotSame(interfaceV1Event4, retargetedClassCEvent4Impl); Assert.Equal(retargetedClassCEvent4Impl.Name, interfaceV1Event4.Name); Assert.Equal(retargetedClassCEvent4Impl.Type.ToTestDisplayString(), interfaceV1Event4.Type.ToTestDisplayString()); } } private static PropertySymbol FindIndexerWithParameterCount(NamedTypeSymbol type, int parameterCount) { return type.GetMembers().Where(s => s.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single(p => p.Parameters.Length == parameterCount); } [Fact] public void ExplicitInterfaceImplementationRetargetingGeneric() { var comp1 = CreateCompilation( new AssemblyIdentity("Assembly1"), new string[] { @" public class C1<S> : Interface2<S> { void Interface2<S>.Method1(S s) { } S Interface2<S>.Property1 { get; set; } event System.Action<S> Interface2<S>.Event1 { add { } remove { } } } public class C2 : Interface2<int> { void Interface2<int>.Method1(int i) { } int Interface2<int>.Property1 { get; set; } event System.Action<int> Interface2<int>.Event1 { add { } remove { } } } public class C3 : Interface2<Class1> { void Interface2<Class1>.Method1(Class1 c) { } Class1 Interface2<Class1>.Property1 { get; set; } event System.Action<Class1> Interface2<Class1>.Event1 { add { } remove { } } } " }, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, }); var d = comp1.GetDiagnostics(); Assert.False(comp1.GetDiagnostics().Any()); var globalNamespace1 = comp1.GlobalNamespace; var classC1 = globalNamespace1.GetTypeMembers("C1").Single(); var classC2 = globalNamespace1.GetTypeMembers("C2").Single(); var classC3 = globalNamespace1.GetTypeMembers("C3").Single(); foreach (var diag in comp1.GetDiagnostics()) { Console.WriteLine(diag); } var comp2 = CreateCompilation( new AssemblyIdentity("Assembly2"), new string[] {@" public class D1<R> : C1<R> { } public class D2 : C2 { } public class D3 : C3 { } " }, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(comp1) }); Assert.False(comp2.GetDiagnostics().Any()); var globalNamespace2 = comp2.GlobalNamespace; var interfaceV2 = globalNamespace2.GetTypeMembers("Interface2").Single(); var interfaceV2Method1 = interfaceV2.GetMembers("Method1").Single(); var interfaceV2Property1 = interfaceV2.GetMembers("Property1").Single(); var interfaceV2Event1 = interfaceV2.GetMembers("Event1").Single(); var classD1 = globalNamespace2.GetTypeMembers("D1").Single(); var classD2 = globalNamespace2.GetTypeMembers("D2").Single(); var classD3 = globalNamespace2.GetTypeMembers("D3").Single(); var retargetedClassC1 = classD1.BaseType(); var retargetedClassC2 = classD2.BaseType(); var retargetedClassC3 = classD3.BaseType(); var retargetedClassC1Method1 = (MethodSymbol)retargetedClassC1.GetMembers("Interface2<S>.Method1").Single(); var retargetedClassC1Method1Impl = retargetedClassC1Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC1Method1Impl.OriginalDefinition); var retargetedClassC2Method1 = (MethodSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Method1").Single(); var retargetedClassC2Method1Impl = retargetedClassC2Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC2Method1Impl.OriginalDefinition); var retargetedClassC3Method1 = (MethodSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Method1").Single(); var retargetedClassC3Method1Impl = retargetedClassC3Method1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Method1, retargetedClassC3Method1Impl.OriginalDefinition); var retargetedClassC1Property1 = (PropertySymbol)retargetedClassC1.GetMembers("Interface2<S>.Property1").Single(); var retargetedClassC1Property1Impl = retargetedClassC1Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC1Property1Impl.OriginalDefinition); var retargetedClassC2Property1 = (PropertySymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Property1").Single(); var retargetedClassC2Property1Impl = retargetedClassC2Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC2Property1Impl.OriginalDefinition); var retargetedClassC3Property1 = (PropertySymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Property1").Single(); var retargetedClassC3Property1Impl = retargetedClassC3Property1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Property1, retargetedClassC3Property1Impl.OriginalDefinition); var retargetedClassC1Event1 = (EventSymbol)retargetedClassC1.GetMembers("Interface2<S>.Event1").Single(); var retargetedClassC1Event1Impl = retargetedClassC1Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC1Event1Impl.OriginalDefinition); var retargetedClassC2Event1 = (EventSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Event1").Single(); var retargetedClassC2Event1Impl = retargetedClassC2Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC2Event1Impl.OriginalDefinition); var retargetedClassC3Event1 = (EventSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Event1").Single(); var retargetedClassC3Event1Impl = retargetedClassC3Event1.ExplicitInterfaceImplementations.Single(); Assert.Same(interfaceV2Event1, retargetedClassC3Event1Impl.OriginalDefinition); } [Fact] public void ExplicitInterfaceImplementationRetargetingGenericType() { var source1 = @" public class C1<T> { public interface I1 { void M(T x); } } "; var ref1 = CreateEmptyCompilation("").ToMetadataReference(); var compilation1 = CreateCompilation(source1, references: new[] { ref1 }); var source2 = @" public class C2<U> : C1<U>.I1 { void C1<U>.I1.M(U x) {} } "; var compilation2 = CreateCompilation(source2, references: new[] { compilation1.ToMetadataReference(), ref1, CreateEmptyCompilation("").ToMetadataReference() }); var compilation3 = CreateCompilation("", references: new[] { compilation1.ToMetadataReference(), compilation2.ToMetadataReference() }); Assert.NotSame(compilation2.GetTypeByMetadataName("C1`1"), compilation3.GetTypeByMetadataName("C1`1")); var c2 = compilation3.GetTypeByMetadataName("C2`1"); Assert.IsType<RetargetingNamedTypeSymbol>(c2); var m = c2.GetMethod("C1<U>.I1.M"); Assert.Equal(c2.Interfaces().Single().GetMethod("M"), m.ExplicitInterfaceImplementations.Single()); } } }
-1
dotnet/roslyn
55,192
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-28T20:41:43Z
2021-07-28T21:55:57Z
7ffb9182186852204f1e6e32fc62c2d8c863c08b
ee63d8974e4d472be6d481dafb87eb1fc878cb57
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/InitOnlyMemberTests.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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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.InitOnlySetters)] public class InitOnlyMemberTests : CompilingTestBase { // Spec: https://github.com/dotnet/csharplang/blob/main/proposals/init.md // https://github.com/dotnet/roslyn/issues/44685 // test dynamic scenario // test whether reflection use property despite modreq? // test behavior of old compiler with modreq. For example VB [Fact] public void TestCSharp8() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,35): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 35) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); IPropertySymbol publicProperty = property.GetPublicSymbol(); Assert.False(publicProperty.GetMethod.IsInitOnly); Assert.True(publicProperty.SetMethod.IsInitOnly); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInNestedObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } public class Container { public C contained; } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,45): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(6, 45), // (6,70): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 70) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInWithExpression(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = c with { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,15): error CS8400: Feature 'records' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "with").WithArguments("records", "9.0").WithLocation(6, 15), // (6,22): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 22), // (6,47): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 47) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAssignment(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { c.Property = string.Empty; c.Property2 = string.Empty; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,9): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = string.Empty; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(6, 9), // (7,9): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // c.Property2 = string.Empty; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Property2").WithArguments("C.Property2").WithLocation(7, 9) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAttribute(bool useMetadataImage) { string lib_cs = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,7): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property = 42").WithArguments("init-only setters", "9.0").WithLocation(2, 7), // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation() { string source = @" class C { string Property { get; init; } string Property2 { get; } void M(C c) { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,28): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 28), // (9,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(9, 48) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation_InAttribute() { string source = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,32): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public int Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 32), // (8,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(8, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionFromCompilationReference() { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8, assemblyName: "lib"); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { lib.ToMetadataReference() }, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithDynamicArgument(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } public C(int i) { } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(dynamic d) { _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,24): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 24), // (6,49): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 49) ); } [Fact] public void TestInitNotModifier() { string source = @" public class C { public string Property { get; init set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,40): error CS8180: { or ; or => expected // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(4, 40), // (4,40): error CS1007: Property accessor already defined // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(4, 40) ); } [Fact] public void TestWithDuplicateAccessor() { string source = @" public class C { public string Property { set => throw null; init => throw null; } public string Property2 { init => throw null; set => throw null; } public string Property3 { init => throw null; init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS1007: Property accessor already defined // public string Property { set => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(4, 49), // (5,51): error CS1007: Property accessor already defined // public string Property2 { init => throw null; set => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(5, 51), // (6,51): error CS1007: Property accessor already defined // public string Property3 { init => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(6, 51) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "System.String C.Property { set; }", "void C.Property.set", "System.String C.Property2 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property2.init", "System.String C.Property3 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property3.init", "C..ctor()" }); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property2"); Assert.True(property2.SetMethod.IsInitOnly); Assert.True(property2.GetPublicSymbol().SetMethod.IsInitOnly); var property3 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property3"); Assert.True(property3.SetMethod.IsInitOnly); Assert.True(property3.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InThisOrBaseConstructorInitializer() { string source = @" public class C { public string Property { init { throw null; } } public C() : this(Property = null) // 1 { } public C(string s) { } } public class Derived : C { public Derived() : base(Property = null) // 2 { } public Derived(int i) : base(base.Property = null) // 3 { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (5,23): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public C() : this(Property = null) // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(5, 23), // (15,29): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public Derived() : base(Property = null) // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 29), // (19,34): error CS1512: Keyword 'base' is not available in the current context // public Derived(int i) : base(base.Property = null) // 3 Diagnostic(ErrorCode.ERR_BaseInBadContext, "base").WithLocation(19, 34) ); } [Fact] public void TestWithAccessModifiers_Private() { string source = @" public class C { public string Property { get { throw null; } private init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } C() { Property = null; } } public class Other { void M(C c) { _ = new C() { Property = null }; // 2, 3 c.Property = null; // 4 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,17): error CS0122: 'C.C()' is inaccessible due to its protection level // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("C.C()").WithLocation(20, 17), // (20,23): error CS0272: The property or indexer 'C.Property' cannot be used in this context because the set accessor is inaccessible // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property").WithArguments("C.Property").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9) ); } [Fact] public void TestWithAccessModifiers_Protected() { string source = @" public class C { public string Property { get { throw null; } protected init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } public C() { Property = null; } } public class Derived : C { void M(C c) { _ = new C() { Property = null }; // 2 c.Property = null; // 3, 4 Property = null; // 5 } Derived() { _ = new C() { Property = null }; // 6 _ = new Derived() { Property = null }; Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3, 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9), // (22,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(22, 9), // (27,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 6 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(27, 23) ); } [Fact] public void TestWithAccessModifiers_Protected_WithoutGetter() { string source = @" public class C { public string Property { protected init { throw null; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,19): error CS0276: 'C.Property': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public string Property { protected init { throw null; } } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Property").WithArguments("C.Property").WithLocation(4, 19) ); } [Fact] public void OverrideScenarioWithSubstitutions() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { Property = null; // 1 } Derived() { Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,9): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(10, 9) ); var property = (PropertySymbol)comp.GlobalNamespace.GetTypeMember("Derived").BaseTypeNoUseSiteDiagnostics.GetMember("Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ImplementationScenarioWithSubstitutions() { string source = @" public interface I<T> { public string Property { get; init; } } public class CWithInit : I<string> { public string Property { get; init; } } public class CWithoutInit : I<string> // 1 { public string Property { get; set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,29): error CS8804: 'CWithoutInit' does not implement interface member 'I<string>.Property.init'. 'CWithoutInit.Property.set' cannot implement 'I<string>.Property.init'. // public class CWithoutInit : I<string> // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I<string>").WithArguments("CWithoutInit", "I<string>.Property.init", "CWithoutInit.Property.set").WithLocation(10, 29) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("I.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InLambdaOrLocalFunction_InMethodOrDerivedConstructor() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } Derived() { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (12,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(12, 13), // (18,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(18, 13), // (26,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(26, 13), // (32,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(32, 13) ); } [Fact] public void InLambdaOrLocalFunction_InConstructorOrInit() { string source = @" public class C<T> { public string Property { get; init; } C() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } public string Other { init { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(10, 13), // (16,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(16, 13), // (26,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(26, 17), // (32,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(32, 17) ); } [Fact] public void MissingIsInitOnlyType_Property() { string source = @" public class C { public string Property { get => throw null; init { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public string Property { get => throw null; init { } } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 49) ); } [Fact] public void InitOnlyPropertyAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { Property = null; // 1 _ = new C() { Property = null }; } public C() { Property = null; } public string InitOnlyProperty { get { Property = null; // 2 return null; } init { Property = null; } } public string RegularProperty { get { Property = null; // 3 return null; } set { Property = null; // 4 } } public string otherField = (Property = null); // 5 } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 6 } Derived2() { Property = null; } public string InitOnlyProperty2 { get { Property = null; // 7 return null; } init { Property = null; } } public string RegularProperty2 { get { Property = null; // 8 return null; } set { Property = null; // 9 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (21,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(21, 13), // (34,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(34, 13), // (39,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(39, 13), // (43,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.Property' // public string otherField = (Property = null); // 5 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "Property").WithArguments("C.Property").WithLocation(43, 33), // (54,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(54, 9), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(66, 13), // (79,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(79, 13), // (84,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(84, 13) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InitOnlyPropertyAssignmentAllowedInWithInitializer() { string source = @" record C { public int Property { get; init; } void M(C c) { _ = c with { Property = 1 }; } } record Derived : C { } record Derived2 : Derived { void M(C c) { _ = c with { Property = 1 }; _ = this with { Property = 1 }; } } class Other { void M() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void InitOnlyPropertyAssignmentAllowedInWithInitializer_Evaluation() { string source = @" record C { private int field; public int Property { get { return field; } init { field = value; System.Console.Write(""set ""); } } public C Clone() { System.Console.Write(""clone ""); return this; } } class Other { public static void Main() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "clone set 42"); } [Fact] public void EvaluationInitOnlySetter() { string source = @" public class C { public int Property { init { System.Console.Write(value + "" ""); } } public int Property2 { init { System.Console.Write(value); } } C() { System.Console.Write(""Main ""); } static void Main() { _ = new C() { Property = 42, Property2 = 43}; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Main 42 43"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_OverrideAutoProp(bool emitImage) { string parent = @" public class Base { public virtual int Property { get; init; } }"; string source = @" public class C : Base { int field; public override int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; _ = c.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_AutoProp(bool emitImage) { string source = @" public class C { public int Property { get; init; } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var libComp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main 42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_Implementation(bool emitImage) { string parent = @" public interface I { int Property { get; init; } }"; string source = @" public class C : I { int field; public int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { M<C>(); } static void M<T>() where T : I, new() { var t = new T() { Property = 42 }; _ = t.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Fact] public void DisallowedOnStaticMembers() { string source = @" public class C { public static string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,42): error CS8806: The 'init' accessor is not valid on static members // public static string Property { get; init; } Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(4, 42) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void DisallowedOnOtherInstances() { string source = @" public class C { public string Property { get; init; } public C c; public C() { c.Property = null; // 1 } public string InitOnlyProperty { init { c.Property = null; // 2 } } } public class Derived : C { Derived() { c.Property = null; // 3 } public string InitOnlyProperty2 { init { c.Property = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { Property = (c.Property = null) // 5 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(9, 9), // (16,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(16, 13), // (24,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(24, 9), // (31,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(31, 13), // (41,18): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (c.Property = null) // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(41, 18) ); } [Fact] public void DeconstructionAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 } C() { (Property, (Property, Property)) = (null, (null, null)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 10), // (8,21): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 21), // (8,31): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 31) ); } [Fact] public void OutParameterAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { M2(out Property); // 1 } void M2(out string s) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,16): error CS0206: A property or indexer may not be passed as an out or ref parameter // M2(out Property); // 1 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(8, 16) ); } [Fact] public void CompoundAssignmentDisallowed() { string source = @" public class C { public int Property { get; init; } void M() { Property += 42; // 1 } C() { Property += 42; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property += 42; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_OrAssignment() { string source = @" public class C { public bool Property { get; init; } void M() { Property |= true; // 1 } C() { Property |= true; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property |= true; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_NullCoalescingAssignment() { string source = @" public class C { public string Property { get; init; } void M() { Property ??= null; // 1 } C() { Property ??= null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property ??= null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_Increment() { string source = @" public class C { public int Property { get; init; } void M() { Property++; // 1 } C() { Property++; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property++; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void RefProperty() { string source = @" public class C { ref int Property1 { get; init; } ref int Property2 { init; } ref int Property3 { get => throw null; init => throw null; } ref int Property4 { init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,13): error CS8145: Auto-implemented properties cannot return by reference // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "Property1").WithArguments("C.Property1").WithLocation(4, 13), // (4,30): error CS8147: Properties which return by reference cannot have set accessors // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property1.init").WithLocation(4, 30), // (5,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property2 { init; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property2").WithArguments("C.Property2").WithLocation(5, 13), // (6,44): error CS8147: Properties which return by reference cannot have set accessors // ref int Property3 { get => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property3.init").WithLocation(6, 44), // (7,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property4 { init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property4").WithArguments("C.Property4").WithLocation(7, 13) ); } [Fact] public void VerifyPESymbols_Property() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); // PE verification fails: [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var c = (NamedTypeSymbol)m.GlobalNamespace.GetMember("C"); var property = (PropertySymbol)c.GetMembers("Property").Single(); Assert.Equal("System.String C.Property { get; init; }", property.ToTestDisplayString()); Assert.Equal(0, property.CustomModifierCount()); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); AssertEx.Empty(propertyAttributes); var getter = property.GetMethod; Assert.Empty(property.GetMethod.ReturnTypeWithAnnotations.CustomModifiers); Assert.False(getter.IsInitOnly); Assert.False(getter.GetPublicSymbol().IsInitOnly); var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var setter = property.SetMethod; Assert.True(setter.IsInitOnly); Assert.True(setter.GetPublicSymbol().IsInitOnly); var setterAttributes = property.SetMethod.GetAttributes().Select(a => a.ToString()); var modifier = property.SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", modifier.Modifier.ToTestDisplayString()); Assert.False(modifier.IsOptional); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var backingField = (FieldSymbol)c.GetMembers("<Property>k__BackingField").Single(); var backingFieldAttributes = backingField.GetAttributes().Select(a => a.ToString()); Assert.True(backingField.IsReadOnly); if (isSource) { AssertEx.Empty(backingFieldAttributes); } else { AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }, backingFieldAttributes); var peBackingField = (PEFieldSymbol)backingField; Assert.Equal(System.Reflection.FieldAttributes.InitOnly | System.Reflection.FieldAttributes.Private, peBackingField.Flags); } } } [Theory] [InlineData(true)] [InlineData(false)] public void AssignmentDisallowed_PE(bool emitImage) { string lib_cs = @" public class C { public string Property { get; init; } } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class Other { public C c; void M() { c.Property = null; // 1 } public Other() { c.Property = null; // 2 } public string InitOnlyProperty { get { c.Property = null; // 3 return null; } init { c.Property = null; // 4 } } public string RegularProperty { get { c.Property = null; // 5 return null; } set { c.Property = null; // 6 } } } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 7 base.Property = null; // 8 } Derived2() { Property = null; base.Property = null; } public string InitOnlyProperty2 { get { Property = null; // 9 base.Property = null; // 10 return null; } init { Property = null; base.Property = null; } } public string RegularProperty2 { get { Property = null; // 11 base.Property = null; // 12 return null; } set { Property = null; // 13 base.Property = null; // 14 } } } "; var comp = CreateCompilation(source, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(8, 9), // (13,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(13, 9), // (20,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(20, 13), // (25,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(25, 13), // (33,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(33, 13), // (38,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(38, 13), // (51,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(51, 9), // (52,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(52, 9), // (65,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(65, 13), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 10 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(66, 13), // (80,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 11 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(80, 13), // (81,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 12 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(81, 13), // (86,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 13 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(86, 13), // (87,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 14 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(87, 13) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_ReferenceConversion() { string source = @" var x = new DerivedType() { SomethingElse = 42 }; System.Console.Write(x.SomethingElse); public interface ISomething { int Property { get; init; } } public record BaseType : ISomething { int ISomething.Property { get; init; } } public record DerivedType : BaseType { public int SomethingElse { get => ((ISomething)this).Property; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_BoxingConversion() { string source = @" var x = new Type() { SomethingElse = 42 }; public interface ISomething { int Property { get; init; } } public struct Type : ISomething { int ISomething.Property { get; init; } public int SomethingElse { get => throw null; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact] public void OverridingInitOnlyProperty() { string source = @" public class Base { public virtual string Property { get; init; } } public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } // 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(13, 28), // (22,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(22, 28), // (35,28): error CS8803: 'DerivedDerivedWithoutInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { set { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithoutInit.Property", "DerivedGetterOnly.Property").WithLocation(35, 28) ); } [Theory] [InlineData(true)] [InlineData(false)] public void OverridingInitOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public class Base { public virtual string Property { get; init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(8, 28), // (16,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(16, 28) ); } [Fact] public void OverridingRegularProperty() { string source = @" public class Base { public virtual string Property { get; set; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 2 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } // 3 } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(9, 28), // (18,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(18, 28), // (31,28): error CS8803: 'DerivedDerivedWithInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithInit.Property", "DerivedGetterOnly.Property").WithLocation(31, 28) ); } [Fact] public void OverridingGetterOnlyProperty() { string source = @" public class Base { public virtual string Property { get => null; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 2 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 3 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 4 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,44): error CS0546: 'DerivedWithInit.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInit.Property.init", "Base.Property").WithLocation(8, 44), // (12,44): error CS0546: 'DerivedWithoutInit.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; set; } // 2 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInit.Property.set", "Base.Property").WithLocation(12, 44), // (16,39): error CS0546: 'DerivedWithInitSetterOnly.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInitSetterOnly.Property.init", "Base.Property").WithLocation(16, 39), // (20,39): error CS0546: 'DerivedWithoutInitSetterOnly.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { set { } } // 4 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInitSetterOnly.Property.set", "Base.Property").WithLocation(20, 39) ); } [Fact] public void OverridingSetterOnlyProperty() { string source = @" public class Base { public virtual string Property { set { } } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1, 2 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 3 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 4 } public class DerivedWithoutInitGetterOnly : Base { public override string Property { get => null; } // 5 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(8, 28), // (8,39): error CS0545: 'DerivedWithInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithInit.Property.get", "Base.Property").WithLocation(8, 39), // (12,39): error CS0545: 'DerivedWithoutInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; set; } // 3 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInit.Property.get", "Base.Property").WithLocation(12, 39), // (16,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 4 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(16, 28), // (20,39): error CS0545: 'DerivedWithoutInitGetterOnly.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get => null; } // 5 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInitGetterOnly.Property.get", "Base.Property").WithLocation(20, 39) ); } [Fact] public void ImplementingInitOnlyProperty() { string source = @" public interface I { string Property { get; init; } } public class DerivedWithInit : I { public string Property { get; init; } } public class DerivedWithoutInit : I // 1 { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,35): error CS8804: 'DerivedWithoutInit' does not implement interface member 'I.Property.init'. 'DerivedWithoutInit.Property.set' cannot implement 'I.Property.init'. // public class DerivedWithoutInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithoutInit", "I.Property.init", "DerivedWithoutInit.Property.set").WithLocation(10, 35), // (14,42): error CS0535: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.get' // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.get").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.init").WithLocation(18, 45) ); } [Fact] public void ImplementingSetterOnlyProperty() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(6, 32), // (14,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(18, 45) ); } [Fact] public void ObjectCreationOnInterface() { string source = @" public interface I { string Property { set; } string InitProperty { init; } } public class C { void M<T>() where T: I, new() { _ = new T() { Property = null, InitProperty = null }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void HidingInitOnlySetterOnlyProperty() { string source = @" public class Base { public string Property { init { } } } public class Derived : Base { public string Property { init { } } // 1 } public class DerivedWithNew : Base { public new string Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,19): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public string Property { init { } } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property").WithLocation(8, 19) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public interface I { string Property { set; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyEmitDiagnostics(); string source = @" public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(2, 32), // (10,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(10, 42), // (14,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(14, 45) ); } [Fact] public void ImplementingSetterOnlyProperty_Explicitly() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I { string I.Property { init { } } // 1 } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2, 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithInit.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { init { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInit.I.Property.init", "I.Property.set").WithLocation(8, 25), // (12,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(12, 25), // (12,30): error CS8805: Accessors 'DerivedWithInitAndGetter.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInitAndGetter.I.Property.init", "I.Property.set").WithLocation(12, 30) ); } [Fact] public void ImplementingSetterOnlyInitOnlyProperty_Explicitly() { string source = @" public interface I { string Property { init; } } public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(8, 25), // (16,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(16, 25) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyInitOnlyProperty_Metadata_Explicitly(bool emitAsImage) { string lib_cs = @" public interface I { string Property { init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedGetterOnly : I // 2 { string I.Property { get => null; } // 3, 4 } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (4,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(4, 25), // (10,34): error CS0535: 'DerivedGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedGetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedGetterOnly", "I.Property.init").WithLocation(10, 34), // (12,14): error CS0551: Explicit interface implementation 'DerivedGetterOnly.I.Property' is missing accessor 'I.Property.init' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "Property").WithArguments("DerivedGetterOnly.I.Property", "I.Property.init").WithLocation(12, 14), // (12,25): error CS0550: 'DerivedGetterOnly.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedGetterOnly.I.Property.get", "I.Property").WithLocation(12, 25) ); } [Fact] public void DIM_TwoInitOnlySetters() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { init; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithInitWithDefaultImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementation : I1, I2 { string I1.Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (12,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(12, 12), // (16,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(16, 12), // (24,12): warning CS0108: 'IWithInitWithDefaultImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithDefaultImplementation.Property", "I1.Property").WithLocation(24, 12) ); } [Fact] public void DIM_OneInitOnlySetter() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { set; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithoutInitWithNew : I1, I2 { new string Property { set; } } public interface IWithInitWithImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { init { } } } public interface IWithInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { init { } } // 4 } public interface IWithoutInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { set { } } // 5 } public interface IWithoutInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { set { } } } public interface IWithoutInitWithExplicitImplementationOfBoth : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithExplicitImplementation : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithImplementationWithInitOnly : I1, I2 // 6 { public string Property { init { } } } public class CWithImplementationWithoutInitOnly : I1, I2 // 7 { public string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (13,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(13, 12), // (17,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(17, 12), // (31,12): warning CS0108: 'IWithInitWithImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithImplementation.Property", "I1.Property").WithLocation(31, 12), // (40,26): error CS8805: Accessors 'IWithInitWithExplicitImplementationOfI2.I2.Property.init' and 'I2.Property.set' should both be init-only or neither // string I2.Property { init { } } // 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("IWithInitWithExplicitImplementationOfI2.I2.Property.init", "I2.Property.set").WithLocation(40, 26), // (45,26): error CS8805: Accessors 'IWithoutInitWithExplicitImplementationOfI1.I1.Property.set' and 'I1.Property.init' should both be init-only or neither // string I1.Property { set { } } // 5 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("IWithoutInitWithExplicitImplementationOfI1.I1.Property.set", "I1.Property.init").WithLocation(45, 26), // (62,52): error CS8804: 'CWithImplementationWithInitOnly' does not implement interface member 'I2.Property.set'. 'CWithImplementationWithInitOnly.Property.init' cannot implement 'I2.Property.set'. // public class CWithImplementationWithInitOnly : I1, I2 // 6 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I2").WithArguments("CWithImplementationWithInitOnly", "I2.Property.set", "CWithImplementationWithInitOnly.Property.init").WithLocation(62, 52), // (66,51): error CS8804: 'CWithImplementationWithoutInitOnly' does not implement interface member 'I1.Property.init'. 'CWithImplementationWithoutInitOnly.Property.set' cannot implement 'I1.Property.init'. // public class CWithImplementationWithoutInitOnly : I1, I2 // 7 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I1").WithArguments("CWithImplementationWithoutInitOnly", "I1.Property.init", "CWithImplementationWithoutInitOnly.Property.set").WithLocation(66, 51) ); } [Fact] public void EventWithInitOnly() { string source = @" public class C { public event System.Action Event { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,32): error CS0065: 'C.Event': event property must have both add and remove accessors // public event System.Action Event Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "Event").WithArguments("C.Event").WithLocation(4, 32), // (6,9): error CS1055: An add or remove accessor expected // init { } Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "init").WithLocation(6, 9) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "event System.Action C.Event", "C..ctor()" }); } [Fact] public void EventAccessorsAreNotInitOnly() { string source = @" public class C { public event System.Action Event { add { } remove { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var eventSymbol = comp.GlobalNamespace.GetMember<EventSymbol>("C.Event"); Assert.False(eventSymbol.AddMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().AddMethod.IsInitOnly); Assert.False(eventSymbol.RemoveMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().RemoveMethod.IsInitOnly); } [Fact] public void ConstructorAndDestructorAreNotInitOnly() { string source = @" public class C { public C() { } ~C() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var constructor = comp.GlobalNamespace.GetMember<SourceConstructorSymbol>("C..ctor"); Assert.False(constructor.IsInitOnly); Assert.False(constructor.GetPublicSymbol().IsInitOnly); var destructor = comp.GlobalNamespace.GetMember<SourceDestructorSymbol>("C.Finalize"); Assert.False(destructor.IsInitOnly); Assert.False(destructor.GetPublicSymbol().IsInitOnly); } [Fact] public void OperatorsAreNotInitOnly() { string source = @" public class C { public static implicit operator int(C c) => throw null; public static bool operator +(C c1, C c2) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var conversion = comp.GlobalNamespace.GetMember<SourceUserDefinedConversionSymbol>("C.op_Implicit"); Assert.False(conversion.IsInitOnly); Assert.False(conversion.GetPublicSymbol().IsInitOnly); var addition = comp.GlobalNamespace.GetMember<SourceUserDefinedOperatorSymbol>("C.op_Addition"); Assert.False(addition.IsInitOnly); Assert.False(addition.GetPublicSymbol().IsInitOnly); } [Fact] public void ConstructedMethodsAreNotInitOnly() { string source = @" public class C { void M<T>() { M<string>(); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var invocation = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var method = (IMethodSymbol)model.GetSymbolInfo(invocation).Symbol; Assert.Equal("void C.M<System.String>()", method.ToTestDisplayString()); Assert.False(method.IsInitOnly); } [Fact] public void InitOnlyOnMembersOfRecords() { string source = @" public record C(int i) { void M() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var cMembers = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(); AssertEx.SetEqual(new[] { "C C." + WellKnownMemberNames.CloneMethodName + "()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "C..ctor(System.Int32 i)", "System.Int32 C.<i>k__BackingField", "System.Int32 C.i.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.i.init", "System.Int32 C.i { get; init; }", "void C.M()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 i)", }, cMembers.ToTestDisplayStrings()); foreach (var member in cMembers) { if (member is MethodSymbol method) { bool isSetter = method.MethodKind == MethodKind.PropertySet; Assert.Equal(isSetter, method.IsInitOnly); Assert.Equal(isSetter, method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void IndexerWithInitOnly() { string source = @" public class C { public string this[int i] { init { } } public C() { this[42] = null; } public void M1() { this[43] = null; // 1 } } public class Derived : C { public Derived() { this[44] = null; } public void M2() { this[45] = null; // 2 } } public class D { void M3(C c2) { _ = new C() { [46] = null }; c2[47] = null; // 3 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (14,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[43] = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[43]").WithArguments("C.this[int]").WithLocation(14, 9), // (25,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[45] = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[45]").WithArguments("C.this[int]").WithLocation(25, 9), // (33,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c2[47] = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c2[47]").WithArguments("C.this[int]").WithLocation(33, 9) ); } [Fact] public void ReadonlyFields() { string source = @" public class C { public readonly string field; public C() { field = null; } public void M1() { field = null; // 1 _ = new C() { field = null }; // 2 } public int InitOnlyProperty1 { init { field = null; } } public int RegularProperty { get { field = null; // 3 throw null; } set { field = null; // 4 } } } public class Derived : C { public Derived() { field = null; // 5 } public void M2() { field = null; // 6 } public int InitOnlyProperty2 { init { field = null; // 7 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (11,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(11, 9), // (12,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 23), // (25,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(25, 13), // (30,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(30, 13), // (38,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(38, 9), // (42,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(42, 9), // (48,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 7 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(48, 13) ); } [Fact] public void ReadonlyFields_Evaluation() { string source = @" public class C { public readonly int field; public static void Main() { var c1 = new C(); System.Console.Write($""{c1.field} ""); var c2 = new C() { Property = 43 }; System.Console.Write($""{c2.field}""); } public C() { field = 42; } public int Property { init { field = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "42 43", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] public void ReadonlyFields_TypesDifferingNullability() { string source = @" public class C { public static void Main() { System.Console.Write(C1<int>.F1.content); System.Console.Write("" ""); System.Console.Write(C2<int>.F1.content); } } public struct Container { public int content; } class C1<T> { public static readonly Container F1; static C1() { C1<T>.F1.content = 2; } } #nullable enable class C2<T> { public static readonly Container F1; static C2() { C2<T>.F1.content = 3; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "2 3", verify: Verification.Skipped); // PEVerify bug // [ : C::Main][mdToken=0x6000004][offset 0x00000001] Cannot change initonly field outside its .ctor. v.VerifyIL("C.Main", @" { // Code size 45 (0x2d) .maxstack 1 IL_0000: nop IL_0001: ldsflda ""Container C1<int>.F1"" IL_0006: ldfld ""int Container.content"" IL_000b: call ""void System.Console.Write(int)"" IL_0010: nop IL_0011: ldstr "" "" IL_0016: call ""void System.Console.Write(string)"" IL_001b: nop IL_001c: ldsflda ""Container C2<int>.F1"" IL_0021: ldfld ""int Container.content"" IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop IL_002c: ret } "); } [Fact] public void StaticReadonlyFieldInitializedByAnother() { string source = @" public class C { public static readonly int field; public static readonly int field2 = (field = 42); } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ReadonlyFields_DisallowedOnOtherInstances() { string source = @" public class C { public readonly string field; public C c; public C() { c.field = null; // 1 } public string InitOnlyProperty { init { c.field = null; // 2 } } } public class Derived : C { Derived() { c.field = null; // 3 } public string InitOnlyProperty2 { init { c.field = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { field = // 5 (c.field = null) // 6 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // c.field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(9, 9), // (16,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(16, 13), // (24,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(24, 9), // (31,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(31, 13), // (40,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(40, 13), // (41,18): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // (c.field = null) // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(41, 18) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers() { string source = @" public struct Container { public string content; } public class C { public readonly Container field; public C() { field.content = null; } public void M1() { field.content = null; // 1 } public int InitOnlyProperty1 { init { field.content = null; } } public int RegularProperty { get { field.content = null; // 2 throw null; } set { field.content = null; // 3 } } } public class Derived : C { public Derived() { field.content = null; // 4 } public void M2() { field.content = null; // 5 } public int InitOnlyProperty2 { init { field.content = null; // 6 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (15,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(15, 9), // (28,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(28, 13), // (33,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(33, 13), // (41,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(41, 9), // (45,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(45, 9), // (51,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(51, 13) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Evaluation() { string source = @" public struct Container { public int content; } public class C { public readonly Container field; public int InitOnlyProperty1 { init { field.content = value; System.Console.Write(""RAN ""); } } public static void Main() { var c = new C() { InitOnlyProperty1 = 42 }; System.Console.Write(c.field.content); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Static() { string source = @" public struct Container { public int content; } public static class C { public static readonly Container field; public static int InitOnlyProperty1 { init { field.content = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,9): error CS8856: The 'init' accessor is not valid on static members // init Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(13, 9), // (15,13): error CS1650: Fields of static readonly field 'C.field' cannot be assigned to (except in a static constructor or a variable initializer) // field.content = value; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "field.content").WithArguments("C.field").WithLocation(15, 13) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ReadonlyFields_Metadata(bool emitAsImage) { string lib_cs = @" public class C { public readonly string field; } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class Derived : C { public Derived() { field = null; // 1 _ = new C() { field = null }; // 2 } public void M2() { field = null; // 3 _ = new C() { field = null }; // 4 } public int InitOnlyProperty2 { init { field = null; // 5 } } } "; var comp = CreateCompilation(source, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(6, 9), // (7,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(7, 23), // (12,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 9), // (13,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(13, 23), // (20,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(20, 13) ); } [Fact] public void TestGetSpeculativeSemanticModelForPropertyAccessorBody() { var compilation = CreateCompilation(@" class R { private int _p; } class C : R { private int M { init { int y = 1000; } } } "); var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; _p = 123L; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); AccessorDeclarationSyntax accessorDecl = root.DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); var speculatedMethod = accessorDecl.ReplaceNode(accessorDecl.Body, blockStatement); SemanticModel speculativeModel; var success = model.TryGetSpeculativeSemanticModelForMethodBody( accessorDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var p = speculativeModel.SyntaxTree.GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Single(s => s.Identifier.ValueText == "_p"); var symbolSpeculation = speculativeModel.GetSpeculativeSymbolInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("_p", symbolSpeculation.Symbol.Name); var typeSpeculation = speculativeModel.GetSpeculativeTypeInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Int32", typeSpeculation.Type.Name); } [Fact] public void BlockBodyAndExpressionBody_14() { var comp = CreateCompilation(new[] { @" public class C { static int P1 { get; set; } int P2 { init { P1 = 1; } => P1 = 1; } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // init { P1 = 1; } => P1 = 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "init { P1 = 1; } => P1 = 1;").WithLocation(7, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); Assert.Equal(2, nodes.Count()); foreach (var assign in nodes) { var node = assign.Left; Assert.Equal("P1", node.ToString()); Assert.Equal("System.Int32 C.P1 { get; set; }", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } } [Fact] public void ModReqOnSetAccessorParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.Property.set").WithLocation(4, 36), // (8,25): error CS8853: 'Derived2.Property' must match by init-only of overridden member 'C.Property' // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (8,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.Property.set").WithLocation(8, 36), // (14,11): error CS0570: 'C.Property.set' is not supported by the language // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogus, "Property").WithArguments("C.Property.set").WithLocation(14, 11), // (15,11): error CS0571: 'C.Property.set': cannot explicitly call operator or accessor // c.set_Property(42); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Property").WithArguments("C.Property.set").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.Null(property0.GetMethod); Assert.False(property0.MustCallMethodsDirectly); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_AndProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived.Property", "C.Property").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (14,11): error CS1546: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor method 'C.set_Property(int)' // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Property").WithArguments("C.Property", "C.set_Property(int)").WithLocation(14, 11), // (15,11): error CS0570: 'C.set_Property(int)' is not supported by the language // c.set_Property(42); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.HasUnsupportedMetadata); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Int32", property0.Type.ToTestDisplayString()); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.False(property1.HasUseSiteError); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.False(property2.HasUseSiteError); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_IndexerParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i, int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i) { .set instance void C::set_Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit), int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } public class D { void M(C c) { c[42] = 43; c.set_Item(42, 43); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived.this[int]", "C.this[int]").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (14,9): error CS1546: Property, indexer, or event 'C.this[int]' is not supported by the language; try directly calling accessor method 'C.set_Item(int, int)' // c[42] = 43; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "c[42]").WithArguments("C.this[int]", "C.set_Item(int, int)").WithLocation(14, 9), // (15,11): error CS0570: 'C.set_Item(int, int)' is not supported by the language // c.set_Item(42, 43); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Item").WithArguments("C.set_Item(int, int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnIndexerValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 i, int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 i) { .set instance void C::set_Item(int32, int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.this[int].set").WithLocation(4, 39), // (8,25): error CS8853: 'Derived2.this[int]' must match by init-only of overridden member 'C.this[int]' // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (8,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.this[int].set").WithLocation(8, 39) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.False(property0.HasUseSiteError); Assert.False(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[1].HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticMethod() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.M(); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.M()' is not supported by the language // C.M(); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("C.M()").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticSet() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.P = 2; } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.P.set' is not supported by the language // C.P = 2; Diagnostic(ErrorCode.ERR_BindToBogus, "P").WithArguments("C.P.set").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.set_P"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnMethodParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot virtual instance void M ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override void M() { } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,26): error CS0115: 'Derived.M()': no suitable method found to override // public override void M() { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M").WithArguments("Derived.M()").WithLocation(4, 26) ); var method0 = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.True(method0.HasUseSiteError); Assert.True(method0.HasUnsupportedMetadata); Assert.True(method0.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnInitOnlySetterOfRefProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property() { .get instance int32& C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); c.set_Property(i); // 1 _ = c.Property; // 2 c.Property = i; // 3 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 2 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.False(property0.GetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnRefReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.RefCustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Empty(property0.TypeWithAnnotations.CustomModifiers); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property() .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Empty(property0.RefCustomModifiers); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Equal("System.Int32", property0.TypeWithAnnotations.Type.ToTestDisplayString()); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnGetAccessorReturnValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { get { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.get' is not supported by the language // public override int Property { get { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("C.Property.get").WithLocation(4, 36) ); var property = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.GetMethod.HasUseSiteError); Assert.True(property.GetMethod.HasUnsupportedMetadata); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); Assert.False(property.SetMethod.HasUseSiteError); } [Fact] public void TestSyntaxFacts() { Assert.True(SyntaxFacts.IsAccessorDeclaration(SyntaxKind.InitAccessorDeclaration)); Assert.True(SyntaxFacts.IsAccessorDeclarationKeyword(SyntaxKind.InitKeyword)); } [Fact] public void NoCascadingErrorsInStaticConstructor() { string source = @" public class C { public string Property { get { throw null; } init { throw null; } } static C() { Property = null; // 1 this.Property = null; // 2 } } public class D : C { static D() { Property = null; // 3 this.Property = null; // 4 base.Property = null; // 5 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(7, 9), // (8,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 2 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(8, 9), // (15,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 3 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 9), // (16,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 4 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(16, 9), // (17,9): error CS1511: Keyword 'base' is not available in a static method // base.Property = null; // 5 Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base").WithLocation(17, 9) ); } [Fact] public void LocalFunctionsAreNotInitOnly() { var comp = CreateCompilation(new[] { @" public class C { delegate void Delegate(); void M() { local(); void local() { } } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var localFunctionSyntax = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var localFunctionSymbol = model.GetDeclaredSymbol(localFunctionSyntax).GetSymbol<LocalFunctionSymbol>(); Assert.False(localFunctionSymbol.IsInitOnly); Assert.False(localFunctionSymbol.GetPublicSymbol().IsInitOnly); var delegateSyntax = tree.GetRoot().DescendantNodes().OfType<DelegateDeclarationSyntax>().Single(); var delegateMemberSymbols = model.GetDeclaredSymbol(delegateSyntax).GetSymbol<SourceNamedTypeSymbol>().GetMembers(); Assert.True(delegateMemberSymbols.All(m => m is SourceDelegateMethodSymbol)); foreach (var member in delegateMemberSymbols) { if (member is MethodSymbol method) { Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void RetargetProperties_WithInitOnlySetter() { var source0 = @" public struct S { public int Property { get; init; } } "; var source1 = @" class Program { public static void Main() { var s = new S() { Property = 42 }; System.Console.WriteLine(s.Property); } } "; var source2 = @" class Program { public static void Main() { var s = new S() { Property = 43 }; System.Console.WriteLine(s.Property); } } "; var comp1 = CreateCompilation(new[] { source0, source1, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); // PEVerify: [ : S::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp1, expectedOutput: "42", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp7 = CreateCompilation(source2, references: comp1Ref, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp7, expectedOutput: "43"); var property = comp7.GetMember<PropertySymbol>("S.Property"); var setter = (RetargetingMethodSymbol)property.SetMethod; Assert.True(setter.IsInitOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { public int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { private readonly int i; public int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { public readonly int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { private readonly int i; public readonly int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_AutoProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get; readonly init; } } " }); comp.VerifyDiagnostics( // (4,34): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get; readonly init; } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 34) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ManualProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get => 1; readonly init { } } } " }); comp.VerifyDiagnostics( // (4,39): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get => 1; readonly init { } } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 39) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ReassignsSelf() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I1 = 1, I2 = 2 }; System.Console.WriteLine($""I1 is {s.I1}""); public readonly struct S { private readonly int i; public readonly int I1 { get => i; init => i = value; } public int I2 { get => throw null; init { System.Console.WriteLine($""I1 was {I1}""); this = default; } } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: @"I1 was 1 I1 is 0"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i1 = s.GetMember<IPropertySymbol>("I1"); Assert.False(i1.SetMethod.IsReadOnly); var i2 = s.GetMember<IPropertySymbol>("I2"); Assert.False(i2.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 54 (0x36) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I1.init"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void S.I2.init"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldstr ""I1 is {0}"" IL_001f: ldloca.s V_0 IL_0021: call ""int S.I1.get"" IL_0026: box ""int"" IL_002b: call ""string string.Format(string, object)"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret } "); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,16): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 16) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_NewT() { var source = @" using System; class C { void M<T>(Person person) where T : Container, new() { Container c = new T() { Person = { FirstName = ""c"" } }; } } public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }); comp.VerifyEmitDiagnostics( // (10,24): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(10, 24) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingGenericType() { var source = @" using System; Person person = new Person(""j"", ""p""); var c = new Container<Person>(person) { PropertyT = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container<T>(T PropertyT) where T : Person; "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,19): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // PropertyT = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 19) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNew() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = new Person(""j"", ""p"") { FirstName = ""c"" } }; Console.Write(c.Person.FirstName); public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // PEVerify: Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "c", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNewNoPia() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int Property { get; init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x) { } } "; var piaCompilation = CreateCompilationWithMscorlib45(new[] { IsExternalInitTypeDefinition, pia }, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string source = @" class UsePia { public ITest28 Property2 { get; init; } public static void Main() { var x1 = new ITest28() { Property = 42 }; var x2 = new UsePia() { Property2 = { Property = 43 } }; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,47): error CS8852: Init-only property or indexer 'ITest28.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // var x2 = new UsePia() { Property2 = { Property = 43 } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("ITest28.Property").WithLocation(9, 47) ); } [Fact, WorkItem(50696, "https://github.com/dotnet/roslyn/issues/50696")] public void PickAmbiguousTypeFromCorlib() { var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } "; string source = @" public class C { public int Property { get; init; } } "; var corlibWithoutIsExternalInitRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutIsExternalInit") .EmitToImageReference(); var corlibWithIsExternalInitRef = CreateEmptyCompilation(corlib_cs + IsExternalInitTypeDefinition, assemblyName: "corlibWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef2 = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit2") .EmitToImageReference(); { // type in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in library var comp = CreateEmptyCompilation(new[] { source }, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "libWithIsExternalInit"); } { // type in corlib and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib, in library and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib and in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib in middle) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib last) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, libWithIsExternalInitRef2, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics( // (4,32): error CS018: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in corlib and in a library var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library (reverse order) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics(); Assert.Equal("libWithIsExternalInit", comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal("corlibWithIsExternalInit", comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } static void verify(CSharpCompilation comp, string expectedAssemblyName) { var modifier = ((SourcePropertySymbol)comp.GlobalNamespace.GetMember("C.Property")).SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal(expectedAssemblyName, modifier.Modifier.ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.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 System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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.InitOnlySetters)] public class InitOnlyMemberTests : CompilingTestBase { // Spec: https://github.com/dotnet/csharplang/blob/main/proposals/init.md // https://github.com/dotnet/roslyn/issues/44685 // test dynamic scenario // test whether reflection use property despite modreq? // test behavior of old compiler with modreq. For example VB [Fact] public void TestCSharp8() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,35): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 35) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); IPropertySymbol publicProperty = property.GetPublicSymbol(); Assert.False(publicProperty.GetMethod.IsInitOnly); Assert.True(publicProperty.SetMethod.IsInitOnly); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInNestedObjectInitializer(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } public class Container { public C contained; } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,45): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(6, 45), // (6,70): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new Container() { contained = { Property = string.Empty, Property2 = string.Empty } }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 70) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInWithExpression(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { _ = c with { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,15): error CS8400: Feature 'records' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "with").WithArguments("records", "9.0").WithLocation(6, 15), // (6,22): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 22), // (6,47): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = c with { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 47) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAssignment(bool useMetadataImage) { string lib_cs = @" public record C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(C c) { c.Property = string.Empty; c.Property2 = string.Empty; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,9): error CS8852: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = string.Empty; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(6, 9), // (7,9): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // c.Property2 = string.Empty; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Property2").WithArguments("C.Property2").WithLocation(7, 9) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionInAttribute(bool useMetadataImage) { string lib_cs = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,7): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property = 42").WithArguments("init-only setters", "9.0").WithLocation(2, 7), // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(2, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation() { string source = @" class C { string Property { get; init; } string Property2 { get; } void M(C c) { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,28): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // string Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 28), // (9,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(9, 48) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithinSameCompilation_InAttribute() { string source = @" public class TestAttribute : System.Attribute { public int Property { get; init; } public int Property2 { get; } } [Test(Property = 42, Property2 = 43)] class C { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (4,32): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // public int Property { get; init; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "init").WithArguments("init-only setters", "9.0").WithLocation(4, 32), // (8,22): error CS0617: 'Property2' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [Test(Property = 42, Property2 = 43)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "Property2").WithArguments("Property2").WithLocation(8, 22) ); } [Fact, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionFromCompilationReference() { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular8, assemblyName: "lib"); string source = @" public class D { void M() { _ = new C() { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { lib.ToMetadataReference() }, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (6,23): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 23), // (6,48): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C() { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 48) ); } [Theory, CombinatorialData, WorkItem(50245, "https://github.com/dotnet/roslyn/issues/50245")] public void TestCSharp8_ConsumptionWithDynamicArgument(bool useMetadataImage) { string lib_cs = @" public class C { public string Property { get; init; } public string Property2 { get; } public C(int i) { } } "; var lib = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class D { void M(dynamic d) { _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { useMetadataImage ? lib.EmitToImageReference() : lib.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (6,24): error CS8400: Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Property").WithArguments("init-only setters", "9.0").WithLocation(6, 24), // (6,49): error CS0200: Property or indexer 'C.Property2' cannot be assigned to -- it is read only // _ = new C(d) { Property = string.Empty, Property2 = string.Empty }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Property2").WithArguments("C.Property2").WithLocation(6, 49) ); } [Fact] public void TestInitNotModifier() { string source = @" public class C { public string Property { get; init set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,40): error CS8180: { or ; or => expected // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(4, 40), // (4,40): error CS1007: Property accessor already defined // public string Property { get; init set; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(4, 40) ); } [Fact] public void TestWithDuplicateAccessor() { string source = @" public class C { public string Property { set => throw null; init => throw null; } public string Property2 { init => throw null; set => throw null; } public string Property3 { init => throw null; init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS1007: Property accessor already defined // public string Property { set => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(4, 49), // (5,51): error CS1007: Property accessor already defined // public string Property2 { init => throw null; set => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "set").WithLocation(5, 51), // (6,51): error CS1007: Property accessor already defined // public string Property3 { init => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_DuplicateAccessor, "init").WithLocation(6, 51) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "System.String C.Property { set; }", "void C.Property.set", "System.String C.Property2 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property2.init", "System.String C.Property3 { init; }", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Property3.init", "C..ctor()" }); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property2"); Assert.True(property2.SetMethod.IsInitOnly); Assert.True(property2.GetPublicSymbol().SetMethod.IsInitOnly); var property3 = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property3"); Assert.True(property3.SetMethod.IsInitOnly); Assert.True(property3.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InThisOrBaseConstructorInitializer() { string source = @" public class C { public string Property { init { throw null; } } public C() : this(Property = null) // 1 { } public C(string s) { } } public class Derived : C { public Derived() : base(Property = null) // 2 { } public Derived(int i) : base(base.Property = null) // 3 { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (5,23): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public C() : this(Property = null) // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(5, 23), // (15,29): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // public Derived() : base(Property = null) // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 29), // (19,34): error CS1512: Keyword 'base' is not available in the current context // public Derived(int i) : base(base.Property = null) // 3 Diagnostic(ErrorCode.ERR_BaseInBadContext, "base").WithLocation(19, 34) ); } [Fact] public void TestWithAccessModifiers_Private() { string source = @" public class C { public string Property { get { throw null; } private init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } C() { Property = null; } } public class Other { void M(C c) { _ = new C() { Property = null }; // 2, 3 c.Property = null; // 4 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,17): error CS0122: 'C.C()' is inaccessible due to its protection level // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("C.C()").WithLocation(20, 17), // (20,23): error CS0272: The property or indexer 'C.Property' cannot be used in this context because the set accessor is inaccessible // _ = new C() { Property = null }; // 2, 3 Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property").WithArguments("C.Property").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9) ); } [Fact] public void TestWithAccessModifiers_Protected() { string source = @" public class C { public string Property { get { throw null; } protected init { throw null; } } void M() { _ = new C() { Property = null }; Property = null; // 1 } public C() { Property = null; } } public class Derived : C { void M(C c) { _ = new C() { Property = null }; // 2 c.Property = null; // 3, 4 Property = null; // 5 } Derived() { _ = new C() { Property = null }; // 6 _ = new Derived() { Property = null }; Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (20,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(20, 23), // (21,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3, 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(21, 9), // (22,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(22, 9), // (27,23): error CS1540: Cannot access protected member 'C.Property' via a qualifier of type 'C'; the qualifier must be of type 'Derived' (or derived from it) // _ = new C() { Property = null }; // 6 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "Property").WithArguments("C.Property", "C", "Derived").WithLocation(27, 23) ); } [Fact] public void TestWithAccessModifiers_Protected_WithoutGetter() { string source = @" public class C { public string Property { protected init { throw null; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,19): error CS0276: 'C.Property': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor // public string Property { protected init { throw null; } } Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Property").WithArguments("C.Property").WithLocation(4, 19) ); } [Fact] public void OverrideScenarioWithSubstitutions() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { Property = null; // 1 } Derived() { Property = null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,9): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(10, 9) ); var property = (PropertySymbol)comp.GlobalNamespace.GetTypeMember("Derived").BaseTypeNoUseSiteDiagnostics.GetMember("Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ImplementationScenarioWithSubstitutions() { string source = @" public interface I<T> { public string Property { get; init; } } public class CWithInit : I<string> { public string Property { get; init; } } public class CWithoutInit : I<string> // 1 { public string Property { get; set; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,29): error CS8804: 'CWithoutInit' does not implement interface member 'I<string>.Property.init'. 'CWithoutInit.Property.set' cannot implement 'I<string>.Property.init'. // public class CWithoutInit : I<string> // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I<string>").WithArguments("CWithoutInit", "I<string>.Property.init", "CWithoutInit.Property.set").WithLocation(10, 29) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("I.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InLambdaOrLocalFunction_InMethodOrDerivedConstructor() { string source = @" public class C<T> { public string Property { get; init; } } public class Derived : C<string> { void M() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } Derived() { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (12,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(12, 13), // (18,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(18, 13), // (26,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(26, 13), // (32,13): error CS8802: Init-only property or indexer 'C<string>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<string>.Property").WithLocation(32, 13) ); } [Fact] public void InLambdaOrLocalFunction_InConstructorOrInit() { string source = @" public class C<T> { public string Property { get; init; } C() { System.Action a = () => { Property = null; // 1 }; local(); void local() { Property = null; // 2 } } public string Other { init { System.Action a = () => { Property = null; // 3 }; local(); void local() { Property = null; // 4 } } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(10, 13), // (16,13): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(16, 13), // (26,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(26, 17), // (32,17): error CS8802: Init-only property or indexer 'C<T>.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C<T>.Property").WithLocation(32, 17) ); } [Fact] public void MissingIsInitOnlyType_Property() { string source = @" public class C { public string Property { get => throw null; init { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,49): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public string Property { get => throw null; init { } } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 49) ); } [Fact] public void InitOnlyPropertyAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { Property = null; // 1 _ = new C() { Property = null }; } public C() { Property = null; } public string InitOnlyProperty { get { Property = null; // 2 return null; } init { Property = null; } } public string RegularProperty { get { Property = null; // 3 return null; } set { Property = null; // 4 } } public string otherField = (Property = null); // 5 } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 6 } Derived2() { Property = null; } public string InitOnlyProperty2 { get { Property = null; // 7 return null; } init { Property = null; } } public string RegularProperty2 { get { Property = null; // 8 return null; } set { Property = null; // 9 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9), // (21,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(21, 13), // (34,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(34, 13), // (39,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(39, 13), // (43,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.Property' // public string otherField = (Property = null); // 5 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "Property").WithArguments("C.Property").WithLocation(43, 33), // (54,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(54, 9), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(66, 13), // (79,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(79, 13), // (84,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(84, 13) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.SetMethod.IsInitOnly); Assert.True(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void InitOnlyPropertyAssignmentAllowedInWithInitializer() { string source = @" record C { public int Property { get; init; } void M(C c) { _ = c with { Property = 1 }; } } record Derived : C { } record Derived2 : Derived { void M(C c) { _ = c with { Property = 1 }; _ = this with { Property = 1 }; } } class Other { void M() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void InitOnlyPropertyAssignmentAllowedInWithInitializer_Evaluation() { string source = @" record C { private int field; public int Property { get { return field; } init { field = value; System.Console.Write(""set ""); } } public C Clone() { System.Console.Write(""clone ""); return this; } } class Other { public static void Main() { var c = new C() with { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "clone set 42"); } [Fact] public void EvaluationInitOnlySetter() { string source = @" public class C { public int Property { init { System.Console.Write(value + "" ""); } } public int Property2 { init { System.Console.Write(value); } } C() { System.Console.Write(""Main ""); } static void Main() { _ = new C() { Property = 42, Property2 = 43}; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Main 42 43"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_OverrideAutoProp(bool emitImage) { string parent = @" public class Base { public virtual int Property { get; init; } }"; string source = @" public class C : Base { int field; public override int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; _ = c.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_AutoProp(bool emitImage) { string source = @" public class C { public int Property { get; init; } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { var c = new C() { Property = 42 }; System.Console.Write($""{c.Property}""); } } "; var libComp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main 42"); } [Theory] [InlineData(true)] [InlineData(false)] public void EvaluationInitOnlySetter_Implementation(bool emitImage) { string parent = @" public interface I { int Property { get; init; } }"; string source = @" public class C : I { int field; public int Property { get { System.Console.Write(""get:"" + field + "" ""); return field; } init { field = value; System.Console.Write(""set:"" + value + "" ""); } } public C() { System.Console.Write(""Main ""); } }"; string main = @" public class D { static void Main() { M<C>(); } static void M<T>() where T : I, new() { var t = new T() { Property = 42 }; _ = t.Property; } } "; var libComp = CreateCompilation(new[] { parent, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); var comp = CreateCompilation(new[] { source, main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); libComp = CreateCompilation(new[] { parent, source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp = CreateCompilation(new[] { main }, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "Main set:42 get:42"); } [Fact] public void DisallowedOnStaticMembers() { string source = @" public class C { public static string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,42): error CS8806: The 'init' accessor is not valid on static members // public static string Property { get; init; } Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(4, 42) ); var property = (PropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void DisallowedOnOtherInstances() { string source = @" public class C { public string Property { get; init; } public C c; public C() { c.Property = null; // 1 } public string InitOnlyProperty { init { c.Property = null; // 2 } } } public class Derived : C { Derived() { c.Property = null; // 3 } public string InitOnlyProperty2 { init { c.Property = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { Property = (c.Property = null) // 5 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(9, 9), // (16,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(16, 13), // (24,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(24, 9), // (31,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(31, 13), // (41,18): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (c.Property = null) // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(41, 18) ); } [Fact] public void DeconstructionAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 } C() { (Property, (Property, Property)) = (null, (null, null)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 10), // (8,21): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 21), // (8,31): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // (Property, (Property, Property)) = (null, (null, null)); // 1, 2, 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 31) ); } [Fact] public void OutParameterAssignmentDisallowed() { string source = @" public class C { public string Property { get; init; } void M() { M2(out Property); // 1 } void M2(out string s) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,16): error CS0206: A property or indexer may not be passed as an out or ref parameter // M2(out Property); // 1 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(8, 16) ); } [Fact] public void CompoundAssignmentDisallowed() { string source = @" public class C { public int Property { get; init; } void M() { Property += 42; // 1 } C() { Property += 42; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property += 42; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_OrAssignment() { string source = @" public class C { public bool Property { get; init; } void M() { Property |= true; // 1 } C() { Property |= true; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property |= true; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_NullCoalescingAssignment() { string source = @" public class C { public string Property { get; init; } void M() { Property ??= null; // 1 } C() { Property ??= null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property ??= null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void CompoundAssignmentDisallowed_Increment() { string source = @" public class C { public int Property { get; init; } void M() { Property++; // 1 } C() { Property++; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property++; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(8, 9) ); } [Fact] public void RefProperty() { string source = @" public class C { ref int Property1 { get; init; } ref int Property2 { init; } ref int Property3 { get => throw null; init => throw null; } ref int Property4 { init => throw null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,13): error CS8145: Auto-implemented properties cannot return by reference // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "Property1").WithArguments("C.Property1").WithLocation(4, 13), // (4,30): error CS8147: Properties which return by reference cannot have set accessors // ref int Property1 { get; init; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property1.init").WithLocation(4, 30), // (5,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property2 { init; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property2").WithArguments("C.Property2").WithLocation(5, 13), // (6,44): error CS8147: Properties which return by reference cannot have set accessors // ref int Property3 { get => throw null; init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "init").WithArguments("C.Property3.init").WithLocation(6, 44), // (7,13): error CS8146: Properties which return by reference must have a get accessor // ref int Property4 { init => throw null; } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "Property4").WithArguments("C.Property4").WithLocation(7, 13) ); } [Fact] public void VerifyPESymbols_Property() { string source = @" public class C { public string Property { get; init; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); // PE verification fails: [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var c = (NamedTypeSymbol)m.GlobalNamespace.GetMember("C"); var property = (PropertySymbol)c.GetMembers("Property").Single(); Assert.Equal("System.String C.Property { get; init; }", property.ToTestDisplayString()); Assert.Equal(0, property.CustomModifierCount()); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); AssertEx.Empty(propertyAttributes); var getter = property.GetMethod; Assert.Empty(property.GetMethod.ReturnTypeWithAnnotations.CustomModifiers); Assert.False(getter.IsInitOnly); Assert.False(getter.GetPublicSymbol().IsInitOnly); var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var setter = property.SetMethod; Assert.True(setter.IsInitOnly); Assert.True(setter.GetPublicSymbol().IsInitOnly); var setterAttributes = property.SetMethod.GetAttributes().Select(a => a.ToString()); var modifier = property.SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", modifier.Modifier.ToTestDisplayString()); Assert.False(modifier.IsOptional); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var backingField = (FieldSymbol)c.GetMembers("<Property>k__BackingField").Single(); var backingFieldAttributes = backingField.GetAttributes().Select(a => a.ToString()); Assert.True(backingField.IsReadOnly); if (isSource) { AssertEx.Empty(backingFieldAttributes); } else { AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }, backingFieldAttributes); var peBackingField = (PEFieldSymbol)backingField; Assert.Equal(System.Reflection.FieldAttributes.InitOnly | System.Reflection.FieldAttributes.Private, peBackingField.Flags); } } } [Theory] [InlineData(true)] [InlineData(false)] public void AssignmentDisallowed_PE(bool emitImage) { string lib_cs = @" public class C { public string Property { get; init; } } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class Other { public C c; void M() { c.Property = null; // 1 } public Other() { c.Property = null; // 2 } public string InitOnlyProperty { get { c.Property = null; // 3 return null; } init { c.Property = null; // 4 } } public string RegularProperty { get { c.Property = null; // 5 return null; } set { c.Property = null; // 6 } } } class Derived : C { } class Derived2 : Derived { void M() { Property = null; // 7 base.Property = null; // 8 } Derived2() { Property = null; base.Property = null; } public string InitOnlyProperty2 { get { Property = null; // 9 base.Property = null; // 10 return null; } init { Property = null; base.Property = null; } } public string RegularProperty2 { get { Property = null; // 11 base.Property = null; // 12 return null; } set { Property = null; // 13 base.Property = null; // 14 } } } "; var comp = CreateCompilation(source, references: new[] { emitImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(8, 9), // (13,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(13, 9), // (20,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(20, 13), // (25,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 4 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(25, 13), // (33,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 5 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(33, 13), // (38,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c.Property = null; // 6 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c.Property").WithArguments("C.Property").WithLocation(38, 13), // (51,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 7 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(51, 9), // (52,9): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 8 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(52, 9), // (65,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 9 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(65, 13), // (66,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 10 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(66, 13), // (80,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 11 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(80, 13), // (81,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 12 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(81, 13), // (86,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Property = null; // 13 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("C.Property").WithLocation(86, 13), // (87,13): error CS8802: Init-only property or indexer 'C.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // base.Property = null; // 14 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "base.Property").WithArguments("C.Property").WithLocation(87, 13) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_ReferenceConversion() { string source = @" var x = new DerivedType() { SomethingElse = 42 }; System.Console.Write(x.SomethingElse); public interface ISomething { int Property { get; init; } } public record BaseType : ISomething { int ISomething.Property { get; init; } } public record DerivedType : BaseType { public int SomethingElse { get => ((ISomething)this).Property; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact, WorkItem(50053, "https://github.com/dotnet/roslyn/issues/50053")] public void PrivatelyImplementingInitOnlyProperty_BoxingConversion() { string source = @" var x = new Type() { SomethingElse = 42 }; public interface ISomething { int Property { get; init; } } public struct Type : ISomething { int ISomething.Property { get; init; } public int SomethingElse { get => throw null; init => ((ISomething)this).Property = value; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (13,17): error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // init => ((ISomething)this).Property = value; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "((ISomething)this).Property").WithArguments("ISomething.Property").WithLocation(13, 17) ); } [Fact] public void OverridingInitOnlyProperty() { string source = @" public class Base { public virtual string Property { get; init; } } public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } // 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(13, 28), // (22,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(22, 28), // (35,28): error CS8803: 'DerivedDerivedWithoutInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { set { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithoutInit.Property", "DerivedGetterOnly.Property").WithLocation(35, 28) ); } [Theory] [InlineData(true)] [InlineData(false)] public void OverridingInitOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public class Base { public virtual string Property { get; init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithInit : Base { public override string Property { get; init; } } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 1 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 2 } public class DerivedGetterOnly : Base { public override string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithoutInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInit.Property", "Base.Property").WithLocation(8, 28), // (16,28): error CS8803: 'DerivedWithoutInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { set { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithoutInitSetterOnly.Property", "Base.Property").WithLocation(16, 28) ); } [Fact] public void OverridingRegularProperty() { string source = @" public class Base { public virtual string Property { get; set; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 2 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } } public class DerivedGetterOnly : Base { public override string Property { get => null; } } public class DerivedDerivedWithInit : DerivedGetterOnly { public override string Property { init { } } // 3 } public class DerivedDerivedWithoutInit : DerivedGetterOnly { public override string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(9, 28), // (18,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(18, 28), // (31,28): error CS8803: 'DerivedDerivedWithInit.Property' must match by init-only of overridden member 'DerivedGetterOnly.Property' // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedDerivedWithInit.Property", "DerivedGetterOnly.Property").WithLocation(31, 28) ); } [Fact] public void OverridingGetterOnlyProperty() { string source = @" public class Base { public virtual string Property { get => null; } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 2 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 3 } public class DerivedWithoutInitSetterOnly : Base { public override string Property { set { } } // 4 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,44): error CS0546: 'DerivedWithInit.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; init; } // 1 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInit.Property.init", "Base.Property").WithLocation(8, 44), // (12,44): error CS0546: 'DerivedWithoutInit.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { get; set; } // 2 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInit.Property.set", "Base.Property").WithLocation(12, 44), // (16,39): error CS0546: 'DerivedWithInitSetterOnly.Property.init': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { init { } } // 3 Diagnostic(ErrorCode.ERR_NoSetToOverride, "init").WithArguments("DerivedWithInitSetterOnly.Property.init", "Base.Property").WithLocation(16, 39), // (20,39): error CS0546: 'DerivedWithoutInitSetterOnly.Property.set': cannot override because 'Base.Property' does not have an overridable set accessor // public override string Property { set { } } // 4 Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("DerivedWithoutInitSetterOnly.Property.set", "Base.Property").WithLocation(20, 39) ); } [Fact] public void OverridingSetterOnlyProperty() { string source = @" public class Base { public virtual string Property { set { } } } public class DerivedWithInit : Base { public override string Property { get; init; } // 1, 2 } public class DerivedWithoutInit : Base { public override string Property { get; set; } // 3 } public class DerivedWithInitSetterOnly : Base { public override string Property { init { } } // 4 } public class DerivedWithoutInitGetterOnly : Base { public override string Property { get => null; } // 5 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,28): error CS8803: 'DerivedWithInit.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInit.Property", "Base.Property").WithLocation(8, 28), // (8,39): error CS0545: 'DerivedWithInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; init; } // 1, 2 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithInit.Property.get", "Base.Property").WithLocation(8, 39), // (12,39): error CS0545: 'DerivedWithoutInit.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get; set; } // 3 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInit.Property.get", "Base.Property").WithLocation(12, 39), // (16,28): error CS8803: 'DerivedWithInitSetterOnly.Property' must match by init-only of overridden member 'Base.Property' // public override string Property { init { } } // 4 Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("DerivedWithInitSetterOnly.Property", "Base.Property").WithLocation(16, 28), // (20,39): error CS0545: 'DerivedWithoutInitGetterOnly.Property.get': cannot override because 'Base.Property' does not have an overridable get accessor // public override string Property { get => null; } // 5 Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("DerivedWithoutInitGetterOnly.Property.get", "Base.Property").WithLocation(20, 39) ); } [Fact] public void ImplementingInitOnlyProperty() { string source = @" public interface I { string Property { get; init; } } public class DerivedWithInit : I { public string Property { get; init; } } public class DerivedWithoutInit : I // 1 { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,35): error CS8804: 'DerivedWithoutInit' does not implement interface member 'I.Property.init'. 'DerivedWithoutInit.Property.set' cannot implement 'I.Property.init'. // public class DerivedWithoutInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithoutInit", "I.Property.init", "DerivedWithoutInit.Property.set").WithLocation(10, 35), // (14,42): error CS0535: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.get' // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.get").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.init").WithLocation(18, 45) ); } [Fact] public void ImplementingSetterOnlyProperty() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(6, 32), // (14,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(14, 42), // (18,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(18, 45) ); } [Fact] public void ObjectCreationOnInterface() { string source = @" public interface I { string Property { set; } string InitProperty { init; } } public class C { void M<T>() where T: I, new() { _ = new T() { Property = null, InitProperty = null }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void HidingInitOnlySetterOnlyProperty() { string source = @" public class Base { public string Property { init { } } } public class Derived : Base { public string Property { init { } } // 1 } public class DerivedWithNew : Base { public new string Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,19): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public string Property { init { } } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property").WithLocation(8, 19) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyProperty_Metadata(bool emitAsImage) { string lib_cs = @" public interface I { string Property { set; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyEmitDiagnostics(); string source = @" public class DerivedWithInit : I // 1 { public string Property { get; init; } } public class DerivedWithoutInit : I { public string Property { get; set; } } public class DerivedWithInitSetterOnly : I // 2 { public string Property { init { } } } public class DerivedWithoutInitGetterOnly : I // 3 { public string Property { get => null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (2,32): error CS8804: 'DerivedWithInit' does not implement interface member 'I.Property.set'. 'DerivedWithInit.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInit : I // 1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInit", "I.Property.set", "DerivedWithInit.Property.init").WithLocation(2, 32), // (10,42): error CS8804: 'DerivedWithInitSetterOnly' does not implement interface member 'I.Property.set'. 'DerivedWithInitSetterOnly.Property.init' cannot implement 'I.Property.set'. // public class DerivedWithInitSetterOnly : I // 2 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("DerivedWithInitSetterOnly", "I.Property.set", "DerivedWithInitSetterOnly.Property.init").WithLocation(10, 42), // (14,45): error CS0535: 'DerivedWithoutInitGetterOnly' does not implement interface member 'I.Property.set' // public class DerivedWithoutInitGetterOnly : I // 3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedWithoutInitGetterOnly", "I.Property.set").WithLocation(14, 45) ); } [Fact] public void ImplementingSetterOnlyProperty_Explicitly() { string source = @" public interface I { string Property { set; } } public class DerivedWithInit : I { string I.Property { init { } } // 1 } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2, 3 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithInit.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { init { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInit.I.Property.init", "I.Property.set").WithLocation(8, 25), // (12,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(12, 25), // (12,30): error CS8805: Accessors 'DerivedWithInitAndGetter.I.Property.init' and 'I.Property.set' should both be init-only or neither // string I.Property { get; init; } // 2, 3 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("DerivedWithInitAndGetter.I.Property.init", "I.Property.set").WithLocation(12, 30) ); } [Fact] public void ImplementingSetterOnlyInitOnlyProperty_Explicitly() { string source = @" public interface I { string Property { init; } } public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedWithInitAndGetter : I { string I.Property { get; init; } // 2 } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(8, 25), // (16,25): error CS0550: 'DerivedWithInitAndGetter.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get; init; } // 2 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedWithInitAndGetter.I.Property.get", "I.Property").WithLocation(16, 25) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ImplementingSetterOnlyInitOnlyProperty_Metadata_Explicitly(bool emitAsImage) { string lib_cs = @" public interface I { string Property { init; } }"; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); string source = @" public class DerivedWithoutInit : I { string I.Property { set { } } // 1 } public class DerivedWithInit : I { string I.Property { init { } } } public class DerivedGetterOnly : I // 2 { string I.Property { get => null; } // 3, 4 } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }); comp.VerifyEmitDiagnostics( // (4,25): error CS8805: Accessors 'DerivedWithoutInit.I.Property.set' and 'I.Property.init' should both be init-only or neither // string I.Property { set { } } // 1 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("DerivedWithoutInit.I.Property.set", "I.Property.init").WithLocation(4, 25), // (10,34): error CS0535: 'DerivedGetterOnly' does not implement interface member 'I.Property.init' // public class DerivedGetterOnly : I // 2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("DerivedGetterOnly", "I.Property.init").WithLocation(10, 34), // (12,14): error CS0551: Explicit interface implementation 'DerivedGetterOnly.I.Property' is missing accessor 'I.Property.init' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "Property").WithArguments("DerivedGetterOnly.I.Property", "I.Property.init").WithLocation(12, 14), // (12,25): error CS0550: 'DerivedGetterOnly.I.Property.get' adds an accessor not found in interface member 'I.Property' // string I.Property { get => null; } // 3, 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("DerivedGetterOnly.I.Property.get", "I.Property").WithLocation(12, 25) ); } [Fact] public void DIM_TwoInitOnlySetters() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { init; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithInitWithDefaultImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementation : I1, I2 { string I1.Property { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (12,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(12, 12), // (16,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(16, 12), // (24,12): warning CS0108: 'IWithInitWithDefaultImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithDefaultImplementation.Property", "I1.Property").WithLocation(24, 12) ); } [Fact] public void DIM_OneInitOnlySetter() { string source = @" public interface I1 { string Property { init; } } public interface I2 { string Property { set; } } public interface IWithoutInit : I1, I2 { string Property { set; } // 1 } public interface IWithInit : I1, I2 { string Property { init; } // 2 } public interface IWithInitWithNew : I1, I2 { new string Property { init; } } public interface IWithoutInitWithNew : I1, I2 { new string Property { set; } } public interface IWithInitWithImplementation : I1, I2 { string Property { init { } } // 3 } public interface IWithInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { init { } } } public interface IWithInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { init { } } // 4 } public interface IWithoutInitWithExplicitImplementationOfI1 : I1, I2 { string I1.Property { set { } } // 5 } public interface IWithoutInitWithExplicitImplementationOfI2 : I1, I2 { string I2.Property { set { } } } public interface IWithoutInitWithExplicitImplementationOfBoth : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithExplicitImplementation : I1, I2 { string I1.Property { init { } } string I2.Property { set { } } } public class CWithImplementationWithInitOnly : I1, I2 // 6 { public string Property { init { } } } public class CWithImplementationWithoutInitOnly : I1, I2 // 7 { public string Property { set { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); Assert.True(comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation); comp.VerifyEmitDiagnostics( // (13,12): warning CS0108: 'IWithoutInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { set; } // 1 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithoutInit.Property", "I1.Property").WithLocation(13, 12), // (17,12): warning CS0108: 'IWithInit.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init; } // 2 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInit.Property", "I1.Property").WithLocation(17, 12), // (31,12): warning CS0108: 'IWithInitWithImplementation.Property' hides inherited member 'I1.Property'. Use the new keyword if hiding was intended. // string Property { init { } } // 3 Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("IWithInitWithImplementation.Property", "I1.Property").WithLocation(31, 12), // (40,26): error CS8805: Accessors 'IWithInitWithExplicitImplementationOfI2.I2.Property.init' and 'I2.Property.set' should both be init-only or neither // string I2.Property { init { } } // 4 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "init").WithArguments("IWithInitWithExplicitImplementationOfI2.I2.Property.init", "I2.Property.set").WithLocation(40, 26), // (45,26): error CS8805: Accessors 'IWithoutInitWithExplicitImplementationOfI1.I1.Property.set' and 'I1.Property.init' should both be init-only or neither // string I1.Property { set { } } // 5 Diagnostic(ErrorCode.ERR_ExplicitPropertyMismatchInitOnly, "set").WithArguments("IWithoutInitWithExplicitImplementationOfI1.I1.Property.set", "I1.Property.init").WithLocation(45, 26), // (62,52): error CS8804: 'CWithImplementationWithInitOnly' does not implement interface member 'I2.Property.set'. 'CWithImplementationWithInitOnly.Property.init' cannot implement 'I2.Property.set'. // public class CWithImplementationWithInitOnly : I1, I2 // 6 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I2").WithArguments("CWithImplementationWithInitOnly", "I2.Property.set", "CWithImplementationWithInitOnly.Property.init").WithLocation(62, 52), // (66,51): error CS8804: 'CWithImplementationWithoutInitOnly' does not implement interface member 'I1.Property.init'. 'CWithImplementationWithoutInitOnly.Property.set' cannot implement 'I1.Property.init'. // public class CWithImplementationWithoutInitOnly : I1, I2 // 7 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I1").WithArguments("CWithImplementationWithoutInitOnly", "I1.Property.init", "CWithImplementationWithoutInitOnly.Property.set").WithLocation(66, 51) ); } [Fact] public void EventWithInitOnly() { string source = @" public class C { public event System.Action Event { init { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,32): error CS0065: 'C.Event': event property must have both add and remove accessors // public event System.Action Event Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "Event").WithArguments("C.Event").WithLocation(4, 32), // (6,9): error CS1055: An add or remove accessor expected // init { } Diagnostic(ErrorCode.ERR_AddOrRemoveExpected, "init").WithLocation(6, 9) ); var members = ((NamedTypeSymbol)comp.GlobalNamespace.GetMember("C")).GetMembers(); AssertEx.SetEqual(members.ToTestDisplayStrings(), new[] { "event System.Action C.Event", "C..ctor()" }); } [Fact] public void EventAccessorsAreNotInitOnly() { string source = @" public class C { public event System.Action Event { add { } remove { } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var eventSymbol = comp.GlobalNamespace.GetMember<EventSymbol>("C.Event"); Assert.False(eventSymbol.AddMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().AddMethod.IsInitOnly); Assert.False(eventSymbol.RemoveMethod.IsInitOnly); Assert.False(eventSymbol.GetPublicSymbol().RemoveMethod.IsInitOnly); } [Fact] public void ConstructorAndDestructorAreNotInitOnly() { string source = @" public class C { public C() { } ~C() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var constructor = comp.GlobalNamespace.GetMember<SourceConstructorSymbol>("C..ctor"); Assert.False(constructor.IsInitOnly); Assert.False(constructor.GetPublicSymbol().IsInitOnly); var destructor = comp.GlobalNamespace.GetMember<SourceDestructorSymbol>("C.Finalize"); Assert.False(destructor.IsInitOnly); Assert.False(destructor.GetPublicSymbol().IsInitOnly); } [Fact] public void OperatorsAreNotInitOnly() { string source = @" public class C { public static implicit operator int(C c) => throw null; public static bool operator +(C c1, C c2) => throw null; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var conversion = comp.GlobalNamespace.GetMember<SourceUserDefinedConversionSymbol>("C.op_Implicit"); Assert.False(conversion.IsInitOnly); Assert.False(conversion.GetPublicSymbol().IsInitOnly); var addition = comp.GlobalNamespace.GetMember<SourceUserDefinedOperatorSymbol>("C.op_Addition"); Assert.False(addition.IsInitOnly); Assert.False(addition.GetPublicSymbol().IsInitOnly); } [Fact] public void ConstructedMethodsAreNotInitOnly() { string source = @" public class C { void M<T>() { M<string>(); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var invocation = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var method = (IMethodSymbol)model.GetSymbolInfo(invocation).Symbol; Assert.Equal("void C.M<System.String>()", method.ToTestDisplayString()); Assert.False(method.IsInitOnly); } [Fact] public void InitOnlyOnMembersOfRecords() { string source = @" public record C(int i) { void M() { } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var cMembers = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(); AssertEx.SetEqual(new[] { "C C." + WellKnownMemberNames.CloneMethodName + "()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "C..ctor(System.Int32 i)", "System.Int32 C.<i>k__BackingField", "System.Int32 C.i.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.i.init", "System.Int32 C.i { get; init; }", "void C.M()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 i)", }, cMembers.ToTestDisplayStrings()); foreach (var member in cMembers) { if (member is MethodSymbol method) { bool isSetter = method.MethodKind == MethodKind.PropertySet; Assert.Equal(isSetter, method.IsInitOnly); Assert.Equal(isSetter, method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void IndexerWithInitOnly() { string source = @" public class C { public string this[int i] { init { } } public C() { this[42] = null; } public void M1() { this[43] = null; // 1 } } public class Derived : C { public Derived() { this[44] = null; } public void M2() { this[45] = null; // 2 } } public class D { void M3(C c2) { _ = new C() { [46] = null }; c2[47] = null; // 3 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (14,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[43] = null; // 1 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[43]").WithArguments("C.this[int]").WithLocation(14, 9), // (25,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // this[45] = null; // 2 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "this[45]").WithArguments("C.this[int]").WithLocation(25, 9), // (33,9): error CS8802: Init-only property or indexer 'C.this[int]' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // c2[47] = null; // 3 Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "c2[47]").WithArguments("C.this[int]").WithLocation(33, 9) ); } [Fact] public void ReadonlyFields() { string source = @" public class C { public readonly string field; public C() { field = null; } public void M1() { field = null; // 1 _ = new C() { field = null }; // 2 } public int InitOnlyProperty1 { init { field = null; } } public int RegularProperty { get { field = null; // 3 throw null; } set { field = null; // 4 } } } public class Derived : C { public Derived() { field = null; // 5 } public void M2() { field = null; // 6 } public int InitOnlyProperty2 { init { field = null; // 7 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (11,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(11, 9), // (12,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 23), // (25,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(25, 13), // (30,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(30, 13), // (38,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(38, 9), // (42,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(42, 9), // (48,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 7 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(48, 13) ); } [Fact] public void ReadonlyFields_Evaluation() { string source = @" public class C { public readonly int field; public static void Main() { var c1 = new C(); System.Console.Write($""{c1.field} ""); var c2 = new C() { Property = 43 }; System.Console.Write($""{c2.field}""); } public C() { field = 42; } public int Property { init { field = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // [ : C::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "42 43", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] public void ReadonlyFields_TypesDifferingNullability() { string source = @" public class C { public static void Main() { System.Console.Write(C1<int>.F1.content); System.Console.Write("" ""); System.Console.Write(C2<int>.F1.content); } } public struct Container { public int content; } class C1<T> { public static readonly Container F1; static C1() { C1<T>.F1.content = 2; } } #nullable enable class C2<T> { public static readonly Container F1; static C2() { C2<T>.F1.content = 3; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "2 3", verify: Verification.Skipped); // PEVerify bug // [ : C::Main][mdToken=0x6000004][offset 0x00000001] Cannot change initonly field outside its .ctor. v.VerifyIL("C.Main", @" { // Code size 45 (0x2d) .maxstack 1 IL_0000: nop IL_0001: ldsflda ""Container C1<int>.F1"" IL_0006: ldfld ""int Container.content"" IL_000b: call ""void System.Console.Write(int)"" IL_0010: nop IL_0011: ldstr "" "" IL_0016: call ""void System.Console.Write(string)"" IL_001b: nop IL_001c: ldsflda ""Container C2<int>.F1"" IL_0021: ldfld ""int Container.content"" IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop IL_002c: ret } "); } [Fact] public void StaticReadonlyFieldInitializedByAnother() { string source = @" public class C { public static readonly int field; public static readonly int field2 = (field = 42); } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ReadonlyFields_DisallowedOnOtherInstances() { string source = @" public class C { public readonly string field; public C c; public C() { c.field = null; // 1 } public string InitOnlyProperty { init { c.field = null; // 2 } } } public class Derived : C { Derived() { c.field = null; // 3 } public string InitOnlyProperty2 { init { c.field = null; // 4 } } } public class Caller { void M(C c) { _ = new C() { field = // 5 (c.field = null) // 6 }; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // c.field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(9, 9), // (16,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(16, 13), // (24,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(24, 9), // (31,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // c.field = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(31, 13), // (40,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(40, 13), // (41,18): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // (c.field = null) // 6 Diagnostic(ErrorCode.ERR_AssgReadonly, "c.field").WithLocation(41, 18) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers() { string source = @" public struct Container { public string content; } public class C { public readonly Container field; public C() { field.content = null; } public void M1() { field.content = null; // 1 } public int InitOnlyProperty1 { init { field.content = null; } } public int RegularProperty { get { field.content = null; // 2 throw null; } set { field.content = null; // 3 } } } public class Derived : C { public Derived() { field.content = null; // 4 } public void M2() { field.content = null; // 5 } public int InitOnlyProperty2 { init { field.content = null; // 6 } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (15,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(15, 9), // (28,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(28, 13), // (33,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(33, 13), // (41,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(41, 9), // (45,9): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(45, 9), // (51,13): error CS1648: Members of readonly field 'C.field' cannot be modified (except in a constructor, an init-only member or a variable initializer) // field.content = null; // 6 Diagnostic(ErrorCode.ERR_AssgReadonly2, "field.content").WithArguments("C.field").WithLocation(51, 13) ); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Evaluation() { string source = @" public struct Container { public int content; } public class C { public readonly Container field; public int InitOnlyProperty1 { init { field.content = value; System.Console.Write(""RAN ""); } } public static void Main() { var c = new C() { InitOnlyProperty1 = 42 }; System.Console.Write(c.field.content); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45657, "https://github.com/dotnet/roslyn/issues/45657")] public void ReadonlyFieldsMembers_Static() { string source = @" public struct Container { public int content; } public static class C { public static readonly Container field; public static int InitOnlyProperty1 { init { field.content = value; } } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,9): error CS8856: The 'init' accessor is not valid on static members // init Diagnostic(ErrorCode.ERR_BadInitAccessor, "init").WithLocation(13, 9), // (15,13): error CS1650: Fields of static readonly field 'C.field' cannot be assigned to (except in a static constructor or a variable initializer) // field.content = value; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "field.content").WithArguments("C.field").WithLocation(15, 13) ); } [Theory] [InlineData(true)] [InlineData(false)] public void ReadonlyFields_Metadata(bool emitAsImage) { string lib_cs = @" public class C { public readonly string field; } "; var libComp = CreateCompilation(new[] { lib_cs, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); string source = @" public class Derived : C { public Derived() { field = null; // 1 _ = new C() { field = null }; // 2 } public void M2() { field = null; // 3 _ = new C() { field = null }; // 4 } public int InitOnlyProperty2 { init { field = null; // 5 } } } "; var comp = CreateCompilation(source, references: new[] { emitAsImage ? libComp.EmitToImageReference() : libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the class in which the field is defined or a variable initializer)) // field = null; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(6, 9), // (7,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(7, 23), // (12,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(12, 9), // (13,23): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = new C() { field = null }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(13, 23), // (20,13): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // field = null; // 5 Diagnostic(ErrorCode.ERR_AssgReadonly, "field").WithLocation(20, 13) ); } [Fact] public void TestGetSpeculativeSemanticModelForPropertyAccessorBody() { var compilation = CreateCompilation(@" class R { private int _p; } class C : R { private int M { init { int y = 1000; } } } "); var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; _p = 123L; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); AccessorDeclarationSyntax accessorDecl = root.DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); var speculatedMethod = accessorDecl.ReplaceNode(accessorDecl.Body, blockStatement); SemanticModel speculativeModel; var success = model.TryGetSpeculativeSemanticModelForMethodBody( accessorDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var p = speculativeModel.SyntaxTree.GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Single(s => s.Identifier.ValueText == "_p"); var symbolSpeculation = speculativeModel.GetSpeculativeSymbolInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("_p", symbolSpeculation.Symbol.Name); var typeSpeculation = speculativeModel.GetSpeculativeTypeInfo(p.FullSpan.Start, p, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Int32", typeSpeculation.Type.Name); } [Fact] public void BlockBodyAndExpressionBody_14() { var comp = CreateCompilation(new[] { @" public class C { static int P1 { get; set; } int P2 { init { P1 = 1; } => P1 = 1; } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // init { P1 = 1; } => P1 = 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "init { P1 = 1; } => P1 = 1;").WithLocation(7, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); Assert.Equal(2, nodes.Count()); foreach (var assign in nodes) { var node = assign.Left; Assert.Equal("P1", node.ToString()); Assert.Equal("System.Int32 C.P1 { get; set; }", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } } [Fact] public void ModReqOnSetAccessorParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.Property.set").WithLocation(4, 36), // (8,25): error CS8853: 'Derived2.Property' must match by init-only of overridden member 'C.Property' // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (8,36): error CS0570: 'C.Property.set' is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.Property.set").WithLocation(8, 36), // (14,11): error CS0570: 'C.Property.set' is not supported by the language // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogus, "Property").WithArguments("C.Property.set").WithLocation(14, 11), // (15,11): error CS0571: 'C.Property.set': cannot explicitly call operator or accessor // c.set_Property(42); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Property").WithArguments("C.Property.set").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.Null(property0.GetMethod); Assert.False(property0.MustCallMethodsDirectly); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_AndProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { set { throw null; } } } public class Derived2 : C { public override int Property { init { throw null; } } } public class D { void M(C c) { c.Property = 42; c.set_Property(42); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived.Property", "C.Property").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.Property': cannot override 'C.Property' because it is not supported by the language // public override int Property { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Property").WithArguments("Derived2.Property", "C.Property").WithLocation(8, 25), // (14,11): error CS1546: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor method 'C.set_Property(int)' // c.Property = 42; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Property").WithArguments("C.Property", "C.set_Property(int)").WithLocation(14, 11), // (15,11): error CS0570: 'C.set_Property(int)' is not supported by the language // c.set_Property(42); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.HasUnsupportedMetadata); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Int32", property0.Type.ToTestDisplayString()); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); var property1 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived.Property"); Assert.False(property1.HasUseSiteError); Assert.Null(property1.GetMethod); Assert.False(property1.SetMethod.HasUseSiteError); Assert.False(property1.SetMethod.Parameters[0].Type.IsErrorType()); var property2 = (PropertySymbol)comp.GlobalNamespace.GetMember("Derived2.Property"); Assert.False(property2.HasUseSiteError); Assert.Null(property2.GetMethod); Assert.False(property2.SetMethod.HasUseSiteError); Assert.False(property2.SetMethod.Parameters[0].Type.IsErrorType()); } [Fact] public void ModReqOnSetAccessorParameter_IndexerParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i, int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i) { .set instance void C::set_Item(int32 modreq(System.Runtime.CompilerServices.IsExternalInit), int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } public class D { void M(C c) { c[42] = 43; c.set_Item(42, 43); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): error CS0569: 'Derived.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived.this[int]", "C.this[int]").WithLocation(4, 25), // (8,25): error CS0569: 'Derived2.this[int]': cannot override 'C.this[int]' because it is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (14,9): error CS1546: Property, indexer, or event 'C.this[int]' is not supported by the language; try directly calling accessor method 'C.set_Item(int, int)' // c[42] = 43; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "c[42]").WithArguments("C.this[int]", "C.set_Item(int, int)").WithLocation(14, 9), // (15,11): error CS0570: 'C.set_Item(int, int)' is not supported by the language // c.set_Item(42, 43); Diagnostic(ErrorCode.ERR_BindToBogus, "set_Item").WithArguments("C.set_Item(int, int)").WithLocation(15, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnIndexerValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .custom instance void System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname newslot virtual instance void set_Item ( int32 i, int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Item(int32 i) { .set instance void C::set_Item(int32, int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Reflection.DefaultMemberAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor ( string memberName ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int this[int i] { set { throw null; } } } public class Derived2 : C { public override int this[int i] { init { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { set { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("C.this[int].set").WithLocation(4, 39), // (8,25): error CS8853: 'Derived2.this[int]' must match by init-only of overridden member 'C.this[int]' // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "this").WithArguments("Derived2.this[int]", "C.this[int]").WithLocation(8, 25), // (8,39): error CS0570: 'C.this[int].set' is not supported by the language // public override int this[int i] { init { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "init").WithArguments("C.this[int].set").WithLocation(8, 39) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.this[]"); Assert.False(property0.HasUseSiteError); Assert.False(property0.MustCallMethodsDirectly); Assert.Null(property0.GetMethod); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[1].HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticMethod() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.M(); } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.M()' is not supported by the language // C.M(); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("C.M()").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnStaticSet() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M2() { C.P = 2; } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,11): error CS0570: 'C.P.set' is not supported by the language // C.P = 2; Diagnostic(ErrorCode.ERR_BindToBogus, "P").WithArguments("C.P.set").WithLocation(6, 11) ); var method = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.set_P"); Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); Assert.True(method.HasUseSiteError); Assert.True(method.HasUnsupportedMetadata); } [Fact] public void ModReqOnMethodParameter() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot virtual instance void M ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) i ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override void M() { } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,26): error CS0115: 'Derived.M()': no suitable method found to override // public override void M() { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M").WithArguments("Derived.M()").WithLocation(4, 26) ); var method0 = (PEMethodSymbol)comp.GlobalNamespace.GetMember("C.M"); Assert.True(method0.HasUseSiteError); Assert.True(method0.HasUnsupportedMetadata); Assert.True(method0.Parameters[0].HasUnsupportedMetadata); } [Fact] public void ModReqOnInitOnlySetterOfRefProperty() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property() { .get instance int32& C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); c.set_Property(i); // 1 _ = c.Property; // 2 c.Property = i; // 3 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 2 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.False(property0.GetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnRefReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.RefCustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Empty(property0.TypeWithAnnotations.CustomModifiers); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnRefProperty_OnReturn() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property() .set instance void C::set_Property(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void M(C c, ref int i) { _ = c.get_Property(); // 1 c.set_Property(i); // 2 _ = c.Property; // 3 c.Property = i; // 4 } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS0570: 'C.get_Property()' is not supported by the language // _ = c.get_Property(); // 1 Diagnostic(ErrorCode.ERR_BindToBogus, "get_Property").WithArguments("C.get_Property()").WithLocation(6, 15), // (7,11): error CS0570: 'C.set_Property(ref int)' is not supported by the language // c.set_Property(i); // 2 Diagnostic(ErrorCode.ERR_BindToBogus, "set_Property").WithArguments("C.set_Property(ref int)").WithLocation(7, 11), // (9,15): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // _ = c.Property; // 3 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(9, 15), // (10,11): error CS1545: Property, indexer, or event 'C.Property' is not supported by the language; try directly calling accessor methods 'C.get_Property()' or 'C.set_Property(ref int)' // c.Property = i; // 4 Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Property").WithArguments("C.Property", "C.get_Property()", "C.set_Property(ref int)").WithLocation(10, 11) ); var property0 = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.True(property0.HasUseSiteError); Assert.True(property0.MustCallMethodsDirectly); Assert.Empty(property0.RefCustomModifiers); Assert.Equal("System.Runtime.CompilerServices.IsExternalInit", property0.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString()); Assert.Equal("System.Int32", property0.TypeWithAnnotations.Type.ToTestDisplayString()); Assert.True(property0.GetMethod.HasUseSiteError); Assert.True(property0.GetMethod.HasUnsupportedMetadata); Assert.True(property0.GetMethod.ReturnsByRef); Assert.True(property0.SetMethod.HasUseSiteError); Assert.True(property0.SetMethod.HasUnsupportedMetadata); Assert.True(property0.SetMethod.Parameters[0].HasUnsupportedMetadata); Assert.False(property0.SetMethod.IsInitOnly); Assert.False(property0.GetPublicSymbol().SetMethod.IsInitOnly); } [Fact] public void ModReqOnGetAccessorReturnValue() { string il = @" .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property() .set instance void C::set_Property(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class Derived : C { public override int Property { get { throw null; } } } "; var reference = CreateMetadataReferenceFromIlSource(il); var comp = CreateCompilation(source, references: new[] { reference }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,36): error CS0570: 'C.Property.get' is not supported by the language // public override int Property { get { throw null; } } Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("C.Property.get").WithLocation(4, 36) ); var property = (PEPropertySymbol)comp.GlobalNamespace.GetMember("C.Property"); Assert.False(property.GetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().GetMethod.IsInitOnly); Assert.True(property.GetMethod.HasUseSiteError); Assert.True(property.GetMethod.HasUnsupportedMetadata); Assert.False(property.SetMethod.IsInitOnly); Assert.False(property.GetPublicSymbol().SetMethod.IsInitOnly); Assert.False(property.SetMethod.HasUseSiteError); } [Fact] public void TestSyntaxFacts() { Assert.True(SyntaxFacts.IsAccessorDeclaration(SyntaxKind.InitAccessorDeclaration)); Assert.True(SyntaxFacts.IsAccessorDeclarationKeyword(SyntaxKind.InitKeyword)); } [Fact] public void NoCascadingErrorsInStaticConstructor() { string source = @" public class C { public string Property { get { throw null; } init { throw null; } } static C() { Property = null; // 1 this.Property = null; // 2 } } public class D : C { static D() { Property = null; // 3 this.Property = null; // 4 base.Property = null; // 5 } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 1 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(7, 9), // (8,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 2 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(8, 9), // (15,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // Property = null; // 3 Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(15, 9), // (16,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // this.Property = null; // 4 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(16, 9), // (17,9): error CS1511: Keyword 'base' is not available in a static method // base.Property = null; // 5 Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base").WithLocation(17, 9) ); } [Fact] public void LocalFunctionsAreNotInitOnly() { var comp = CreateCompilation(new[] { @" public class C { delegate void Delegate(); void M() { local(); void local() { } } } ", IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var localFunctionSyntax = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var localFunctionSymbol = model.GetDeclaredSymbol(localFunctionSyntax).GetSymbol<LocalFunctionSymbol>(); Assert.False(localFunctionSymbol.IsInitOnly); Assert.False(localFunctionSymbol.GetPublicSymbol().IsInitOnly); var delegateSyntax = tree.GetRoot().DescendantNodes().OfType<DelegateDeclarationSyntax>().Single(); var delegateMemberSymbols = model.GetDeclaredSymbol(delegateSyntax).GetSymbol<SourceNamedTypeSymbol>().GetMembers(); Assert.True(delegateMemberSymbols.All(m => m is SourceDelegateMethodSymbol)); foreach (var member in delegateMemberSymbols) { if (member is MethodSymbol method) { Assert.False(method.IsInitOnly); Assert.False(method.GetPublicSymbol().IsInitOnly); } } } [Fact] public void RetargetProperties_WithInitOnlySetter() { var source0 = @" public struct S { public int Property { get; init; } } "; var source1 = @" class Program { public static void Main() { var s = new S() { Property = 42 }; System.Console.WriteLine(s.Property); } } "; var source2 = @" class Program { public static void Main() { var s = new S() { Property = 43 }; System.Console.WriteLine(s.Property); } } "; var comp1 = CreateCompilation(new[] { source0, source1, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); // PEVerify: [ : S::set_Property] Cannot change initonly field outside its .ctor. CompileAndVerify(comp1, expectedOutput: "42", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp7 = CreateCompilation(source2, references: comp1Ref, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp7, expectedOutput: "43"); var property = comp7.GetMember<PropertySymbol>("S.Property"); var setter = (RetargetingMethodSymbol)property.SetMethod; Assert.True(setter.IsInitOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { public int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyStruct_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public readonly struct S { private readonly int i; public int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_AutoProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { public readonly int I { get; init; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyProperty_ManualProp() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I = 1 }; System.Console.Write(s.I); public struct S { private readonly int i; public readonly int I { get => i; init => i = value; } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: "1"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I.init"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""readonly int S.I.get"" IL_0019: call ""void System.Console.Write(int)"" IL_001e: ret } "); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_AutoProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get; readonly init; } } " }); comp.VerifyDiagnostics( // (4,34): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get; readonly init; } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 34) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ManualProp() { var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, @" public struct S { public int I { get => 1; readonly init { } } } " }); comp.VerifyDiagnostics( // (4,39): error CS8903: 'init' accessors cannot be marked 'readonly'. Mark 'S.I' readonly instead. // public int I { get => 1; readonly init { } } Diagnostic(ErrorCode.ERR_InitCannotBeReadonly, "init", isSuppressed: false).WithArguments("S.I").WithLocation(4, 39) ); var s = ((Compilation)comp).GetTypeByMetadataName("S"); var i = s.GetMember<IPropertySymbol>("I"); Assert.False(i.SetMethod.IsReadOnly); Assert.True(((Symbols.PublicModel.PropertySymbol)i).GetSymbol<PropertySymbol>().SetMethod.IsDeclaredReadOnly); } [Fact] [WorkItem(47612, "https://github.com/dotnet/roslyn/issues/47612")] public void InitOnlyOnReadonlyInit_ReassignsSelf() { var verifier = CompileAndVerify(new[] { IsExternalInitTypeDefinition, @" var s = new S { I1 = 1, I2 = 2 }; System.Console.WriteLine($""I1 is {s.I1}""); public readonly struct S { private readonly int i; public readonly int I1 { get => i; init => i = value; } public int I2 { get => throw null; init { System.Console.WriteLine($""I1 was {I1}""); this = default; } } } " }, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails, expectedOutput: @"I1 was 1 I1 is 0"); var s = verifier.Compilation.GetTypeByMetadataName("S"); var i1 = s.GetMember<IPropertySymbol>("I1"); Assert.False(i1.SetMethod.IsReadOnly); var i2 = s.GetMember<IPropertySymbol>("I2"); Assert.False(i2.SetMethod.IsReadOnly); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 54 (0x36) .maxstack 2 .locals init (S V_0, //s S V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: call ""void S.I1.init"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void S.I2.init"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldstr ""I1 is {0}"" IL_001f: ldloca.s V_0 IL_0021: call ""int S.I1.get"" IL_0026: box ""int"" IL_002b: call ""string string.Format(string, object)"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret } "); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,16): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 16) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_NewT() { var source = @" using System; class C { void M<T>(Person person) where T : Container, new() { Container c = new T() { Person = { FirstName = ""c"" } }; } } public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }); comp.VerifyEmitDiagnostics( // (10,24): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // Person = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(10, 24) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingGenericType() { var source = @" using System; Person person = new Person(""j"", ""p""); var c = new Container<Person>(person) { PropertyT = { FirstName = ""c"" } }; public record Person(String FirstName, String LastName); public record Container<T>(T PropertyT) where T : Person; "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,19): error CS8852: Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // PropertyT = { FirstName = "c" } Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "FirstName").WithArguments("Person.FirstName").WithLocation(7, 19) ); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNew() { var source = @" using System; Person person = new Person(""j"", ""p""); Container c = new Container(person) { Person = new Person(""j"", ""p"") { FirstName = ""c"" } }; Console.Write(c.Person.FirstName); public record Person(String FirstName, String LastName); public record Container(Person Person); "; var comp = CreateCompilation(new[] { IsExternalInitTypeDefinition, source }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // PEVerify: Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "c", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails); } [Fact] [WorkItem(50126, "https://github.com/dotnet/roslyn/issues/50126")] public void NestedInitializer_UsingNewNoPia() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int Property { get; init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x) { } } "; var piaCompilation = CreateCompilationWithMscorlib45(new[] { IsExternalInitTypeDefinition, pia }, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string source = @" class UsePia { public ITest28 Property2 { get; init; } public static void Main() { var x1 = new ITest28() { Property = 42 }; var x2 = new UsePia() { Property2 = { Property = 43 } }; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,47): error CS8852: Init-only property or indexer 'ITest28.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // var x2 = new UsePia() { Property2 = { Property = 43 } }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "Property").WithArguments("ITest28.Property").WithLocation(9, 47) ); } [Fact, WorkItem(50696, "https://github.com/dotnet/roslyn/issues/50696")] public void PickAmbiguousTypeFromCorlib() { var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } "; string source = @" public class C { public int Property { get; init; } } "; var corlibWithoutIsExternalInitRef = CreateEmptyCompilation(corlib_cs, assemblyName: "corlibWithoutIsExternalInit") .EmitToImageReference(); var corlibWithIsExternalInitRef = CreateEmptyCompilation(corlib_cs + IsExternalInitTypeDefinition, assemblyName: "corlibWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit") .EmitToImageReference(); var libWithIsExternalInitRef2 = CreateEmptyCompilation(IsExternalInitTypeDefinition, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "libWithIsExternalInit2") .EmitToImageReference(); { // type in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithoutIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in library var comp = CreateEmptyCompilation(new[] { source }, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "libWithIsExternalInit"); } { // type in corlib and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib, in library and in source var comp = CreateEmptyCompilation(new[] { source, IsExternalInitTypeDefinition }, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, assemblyName: "source"); comp.VerifyEmitDiagnostics(); verify(comp, "source"); } { // type in corlib and in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib in middle) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries (corlib last) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, libWithIsExternalInitRef2, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }); comp.VerifyEmitDiagnostics( // (4,32): error CS018: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in two libraries, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithoutIsExternalInitRef, libWithIsExternalInitRef, libWithIsExternalInitRef2 }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics( // (4,32): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported // public int Property { get; init; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "init").WithArguments("System.Runtime.CompilerServices.IsExternalInit").WithLocation(4, 32) ); } { // type in corlib and in a library var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library (reverse order) var comp = CreateEmptyCompilation(source, references: new[] { libWithIsExternalInitRef, corlibWithIsExternalInitRef }); comp.VerifyEmitDiagnostics(); verify(comp, "corlibWithIsExternalInit"); } { // type in corlib and in a library, but flag is set var comp = CreateEmptyCompilation(source, references: new[] { corlibWithIsExternalInitRef, libWithIsExternalInitRef }, options: TestOptions.DebugDll.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); comp.VerifyEmitDiagnostics(); Assert.Equal("libWithIsExternalInit", comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal("corlibWithIsExternalInit", comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } static void verify(CSharpCompilation comp, string expectedAssemblyName) { var modifier = ((SourcePropertySymbol)comp.GlobalNamespace.GetMember("C.Property")).SetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single(); Assert.Equal(expectedAssemblyName, modifier.Modifier.ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit).ContainingAssembly.Name); Assert.Equal(expectedAssemblyName, comp.GetTypeByMetadataName("System.Runtime.CompilerServices.IsExternalInit").ContainingAssembly.Name); } } } }
-1
dotnet/roslyn
55,188
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-28T18:01:23Z
2021-07-28T18:01:37Z
992913af492086ae7c5c4bc3425beb4acca0f9b4
7ffb9182186852204f1e6e32fc62c2d8c863c08b
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/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.AddMissingImports; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports { internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs> { /// <summary> /// The command handler display name /// </summary> public abstract string DisplayName { get; } /// <summary> /// The thread await dialog text shown to the user if the operation takes a long time /// </summary> protected abstract string DialogText { get; } private readonly IThreadingContext _threadingContext; public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Check that the feature is enabled before doing any work var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste); // If the feature is explicitly disabled we can exit early if (optionValue.HasValue && !optionValue.Value) { nextCommandHandler(); return; } // Capture the pre-paste caret position var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretPosition.HasValue) { nextCommandHandler(); return; } // Create a tracking span from the pre-paste caret position that will grow as text is inserted. var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive); // Perform the paste command before adding imports nextCommandHandler(); if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, executionContext, optionValue, trackingSpan); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private void ExecuteCommandWorker( PasteCommandArgs args, CommandExecutionContext executionContext, bool? optionValue, ITrackingSpan trackingSpan) { if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace()) { return; } // Don't perform work if we're inside the interactive window if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer)) { return; } // Applying the post-paste snapshot to the tracking span gives us the span of pasted text. var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var sourceTextContainer = args.SubjectBuffer.AsTextContainer(); if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { return; } var document = sourceTextContainer.GetOpenDocumentInCurrentContext(); if (document is null) { return; } // Enable by default unless the user has explicitly disabled in the settings var disabled = optionValue.HasValue && !optionValue.Value; if (disabled) { return; } using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText); var cancellationToken = executionContext.OperationContext.UserCancellationToken; // We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is // intended to tell us how long we're blocking the user from typing with this action. using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>(); #pragma warning disable VSTHRD102 // Implement internal logic asynchronously var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken)); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously if (updatedDocument is null) { return; } workspace.TryApplyChanges(updatedDocument.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. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.AddMissingImports; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports { internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs> { /// <summary> /// The command handler display name /// </summary> public abstract string DisplayName { get; } /// <summary> /// The thread await dialog text shown to the user if the operation takes a long time /// </summary> protected abstract string DialogText { get; } private readonly IThreadingContext _threadingContext; public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Check that the feature is enabled before doing any work var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste); // If the feature is explicitly disabled we can exit early if (optionValue.HasValue && !optionValue.Value) { nextCommandHandler(); return; } // Capture the pre-paste caret position var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretPosition.HasValue) { nextCommandHandler(); return; } // Create a tracking span from the pre-paste caret position that will grow as text is inserted. var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive); // Perform the paste command before adding imports nextCommandHandler(); if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, executionContext, optionValue, trackingSpan); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private void ExecuteCommandWorker( PasteCommandArgs args, CommandExecutionContext executionContext, bool? optionValue, ITrackingSpan trackingSpan) { if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace()) { return; } // Don't perform work if we're inside the interactive window if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer)) { return; } // Applying the post-paste snapshot to the tracking span gives us the span of pasted text. var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var sourceTextContainer = args.SubjectBuffer.AsTextContainer(); if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { return; } var document = sourceTextContainer.GetOpenDocumentInCurrentContext(); if (document is null) { return; } // Enable by default unless the user has explicitly disabled in the settings var disabled = optionValue.HasValue && !optionValue.Value; if (disabled) { return; } using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText); var cancellationToken = executionContext.OperationContext.UserCancellationToken; // We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is // intended to tell us how long we're blocking the user from typing with this action. using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>(); #pragma warning disable VSTHRD102 // Implement internal logic asynchronously var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken)); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously if (updatedDocument is null) { return; } workspace.TryApplyChanges(updatedDocument.Project.Solution); } } }
1