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
unknown
date_merged
unknown
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
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(IErrorTag))] internal partial class DiagnosticsSuggestionTaggerProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { private static readonly IEnumerable<Option2<bool>> s_tagSourceOptions = ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles); protected override IEnumerable<Option2<bool>> Options => s_tagSourceOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticsSuggestionTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, globalOptions, listenerProvider) { } protected internal override bool IncludeDiagnostic(DiagnosticData diagnostic) => diagnostic.Severity == DiagnosticSeverity.Info; protected override IErrorTag CreateTag(Workspace workspace, DiagnosticData diagnostic) => new ErrorTag( PredefinedErrorTypeNames.HintedSuggestion, CreateToolTipContent(workspace, diagnostic)); protected override SnapshotSpan AdjustSnapshotSpan(SnapshotSpan snapshotSpan, int minimumLength) { // We always want suggestion tags to be two characters long. return AdjustSnapshotSpan(snapshotSpan, minimumLength: 2, maximumLength: 2); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(IErrorTag))] internal partial class DiagnosticsSuggestionTaggerProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { private static readonly IEnumerable<Option2<bool>> s_tagSourceOptions = ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles); protected override IEnumerable<Option2<bool>> Options => s_tagSourceOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticsSuggestionTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, globalOptions, listenerProvider) { } protected internal override bool IncludeDiagnostic(DiagnosticData diagnostic) => diagnostic.Severity == DiagnosticSeverity.Info; protected override IErrorTag CreateTag(Workspace workspace, DiagnosticData diagnostic) => new ErrorTag( PredefinedErrorTypeNames.HintedSuggestion, CreateToolTipContent(workspace, diagnostic)); protected override SnapshotSpan AdjustSnapshotSpan(SnapshotSpan snapshotSpan, int minimumLength) { // We always want suggestion tags to be two characters long. return AdjustSnapshotSpan(snapshotSpan, minimumLength: 2, maximumLength: 2); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./CODE-OF-CONDUCT.md
# Code of Conduct This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
# Code of Conduct This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/CSharp/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/WorkspacePullDiagnosticHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(VSInternalMethods.WorkspacePullDiagnosticName)] internal class WorkspacePullDiagnosticHandler : AbstractPullDiagnosticHandler<VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspacePullDiagnosticHandler( IXamlPullDiagnosticService xamlPullDiagnosticService) : base(xamlPullDiagnosticService) { } public override string Method => VSInternalMethods.WorkspacePullDiagnosticName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(VSInternalWorkspaceDiagnosticsParams request) => null; protected override VSInternalWorkspaceDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) => new VSInternalWorkspaceDiagnosticReport { TextDocument = identifier, Diagnostics = diagnostics, ResultId = resultId }; /// <summary> /// Collect all the opened documents from solution. /// In XamlLanguageService, we are only able to retrieve diagnostic information for opened documents. /// So this is the same error experience we have now in full VS scenario. /// </summary> protected override ImmutableArray<Document> GetDocuments(RequestContext context) { Contract.ThrowIfNull(context.Solution); using var _ = ArrayBuilder<Document>.GetInstance(out var result); var projects = context.Solution.GetXamlProjects(); foreach (var project in projects) { result.AddRange(project.Documents); } return result.Distinct().ToImmutableArray(); } protected override VSInternalDiagnosticParams[]? GetPreviousResults(VSInternalWorkspaceDiagnosticsParams diagnosticsParams) => diagnosticsParams.PreviousResults; protected override IProgress<VSInternalWorkspaceDiagnosticReport[]>? GetProgress(VSInternalWorkspaceDiagnosticsParams diagnosticsParams) => diagnosticsParams.PartialResultToken; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(VSInternalMethods.WorkspacePullDiagnosticName)] internal class WorkspacePullDiagnosticHandler : AbstractPullDiagnosticHandler<VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspacePullDiagnosticHandler( IXamlPullDiagnosticService xamlPullDiagnosticService) : base(xamlPullDiagnosticService) { } public override string Method => VSInternalMethods.WorkspacePullDiagnosticName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(VSInternalWorkspaceDiagnosticsParams request) => null; protected override VSInternalWorkspaceDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId) => new VSInternalWorkspaceDiagnosticReport { TextDocument = identifier, Diagnostics = diagnostics, ResultId = resultId }; /// <summary> /// Collect all the opened documents from solution. /// In XamlLanguageService, we are only able to retrieve diagnostic information for opened documents. /// So this is the same error experience we have now in full VS scenario. /// </summary> protected override ImmutableArray<Document> GetDocuments(RequestContext context) { Contract.ThrowIfNull(context.Solution); using var _ = ArrayBuilder<Document>.GetInstance(out var result); var projects = context.Solution.GetXamlProjects(); foreach (var project in projects) { result.AddRange(project.Documents); } return result.Distinct().ToImmutableArray(); } protected override VSInternalDiagnosticParams[]? GetPreviousResults(VSInternalWorkspaceDiagnosticsParams diagnosticsParams) => diagnosticsParams.PreviousResults; protected override IProgress<VSInternalWorkspaceDiagnosticReport[]>? GetProgress(VSInternalWorkspaceDiagnosticsParams diagnosticsParams) => diagnosticsParams.PartialResultToken; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/VisualBasic/Portable/Binding/ForOrForEachBlockBinder.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.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used to bind For and ForEach blocks. ''' It hosts the control variable (if one is declared) ''' and inherits ExitableStatementBinder to provide Continue/Exit labels if needed. ''' </summary> Friend NotInheritable Class ForOrForEachBlockBinder Inherits ExitableStatementBinder Private ReadOnly _syntax As ForOrForEachBlockSyntax Private _locals As ImmutableArray(Of LocalSymbol) = Nothing Public Sub New(enclosing As Binder, syntax As ForOrForEachBlockSyntax) MyBase.New(enclosing, SyntaxKind.ContinueForStatement, SyntaxKind.ExitForStatement) Debug.Assert(syntax IsNot Nothing) _syntax = syntax End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get If _locals.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing) End If Return _locals End Get End Property ' Build a read only array of all the local variables declared By the For statement. ' There can only be 0 or 1 variable. Private Function BuildLocals() As ImmutableArray(Of LocalSymbol) Dim localVar As LocalSymbol = Nothing Dim controlVariableSyntax As VisualBasicSyntaxNode If _syntax.Kind = SyntaxKind.ForBlock Then controlVariableSyntax = DirectCast(_syntax.ForOrForEachStatement, ForStatementSyntax).ControlVariable Else controlVariableSyntax = DirectCast(_syntax.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable End If Dim declarator = TryCast(controlVariableSyntax, VariableDeclaratorSyntax) If declarator IsNot Nothing Then ' Note: ' if the AsClause is nothing _AND_ a nullable modifier is used _AND_ Option Infer is On ' the control variable will not get an inferred type. ' The only difference for Option Infer On and Off is the fact whether the type (Object) is considered ' implicit or explicit. Debug.Assert(declarator.Names.Count = 1) Dim modifiedIdentifier As ModifiedIdentifierSyntax = declarator.Names(0) localVar = LocalSymbol.Create(Me.ContainingMember, Me, modifiedIdentifier.Identifier, modifiedIdentifier, declarator.AsClause, declarator.Initializer, If(_syntax.Kind = SyntaxKind.ForEachBlock, LocalDeclarationKind.ForEach, LocalDeclarationKind.For)) Else Dim identifierName = TryCast(controlVariableSyntax, IdentifierNameSyntax) If identifierName IsNot Nothing Then Dim identifier = identifierName.Identifier If OptionInfer Then Dim result = LookupResult.GetInstance() ContainingBinder.Lookup(result, identifier.ValueText, 0, LookupOptions.AllMethodsOfAnyArity, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) ' If there was something found we do not create a new local of an inferred type. ' The only exception is if all symbols (should be one only, or the result is not good) are type symbols. ' It's perfectly legal to create a local named with the same name as the enclosing type. If Not (result.IsGoodOrAmbiguous AndAlso result.Symbols(0).Kind <> SymbolKind.NamedType AndAlso result.Symbols(0).Kind <> SymbolKind.TypeParameter) Then localVar = CreateLocalSymbol(identifier) End If result.Free() End If End If End If If localVar IsNot Nothing Then Return ImmutableArray.Create(localVar) End If Return ImmutableArray(Of LocalSymbol).Empty End Function Private Function CreateLocalSymbol(identifier As SyntaxToken) As LocalSymbol If _syntax.Kind = SyntaxKind.ForBlock Then Dim forStatementSyntax = DirectCast(_syntax.ForOrForEachStatement, ForStatementSyntax) Dim localVar = LocalSymbol.CreateInferredForFromTo(Me.ContainingMember, Me, identifier, forStatementSyntax.FromValue, forStatementSyntax.ToValue, forStatementSyntax.StepClause) Return localVar Else Dim forEachStatementSyntax = DirectCast(_syntax.ForOrForEachStatement, ForEachStatementSyntax) Dim localVar = LocalSymbol.CreateInferredForEach(Me.ContainingMember, Me, identifier, forEachStatementSyntax.Expression) Return localVar End If End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used to bind For and ForEach blocks. ''' It hosts the control variable (if one is declared) ''' and inherits ExitableStatementBinder to provide Continue/Exit labels if needed. ''' </summary> Friend NotInheritable Class ForOrForEachBlockBinder Inherits ExitableStatementBinder Private ReadOnly _syntax As ForOrForEachBlockSyntax Private _locals As ImmutableArray(Of LocalSymbol) = Nothing Public Sub New(enclosing As Binder, syntax As ForOrForEachBlockSyntax) MyBase.New(enclosing, SyntaxKind.ContinueForStatement, SyntaxKind.ExitForStatement) Debug.Assert(syntax IsNot Nothing) _syntax = syntax End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get If _locals.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing) End If Return _locals End Get End Property ' Build a read only array of all the local variables declared By the For statement. ' There can only be 0 or 1 variable. Private Function BuildLocals() As ImmutableArray(Of LocalSymbol) Dim localVar As LocalSymbol = Nothing Dim controlVariableSyntax As VisualBasicSyntaxNode If _syntax.Kind = SyntaxKind.ForBlock Then controlVariableSyntax = DirectCast(_syntax.ForOrForEachStatement, ForStatementSyntax).ControlVariable Else controlVariableSyntax = DirectCast(_syntax.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable End If Dim declarator = TryCast(controlVariableSyntax, VariableDeclaratorSyntax) If declarator IsNot Nothing Then ' Note: ' if the AsClause is nothing _AND_ a nullable modifier is used _AND_ Option Infer is On ' the control variable will not get an inferred type. ' The only difference for Option Infer On and Off is the fact whether the type (Object) is considered ' implicit or explicit. Debug.Assert(declarator.Names.Count = 1) Dim modifiedIdentifier As ModifiedIdentifierSyntax = declarator.Names(0) localVar = LocalSymbol.Create(Me.ContainingMember, Me, modifiedIdentifier.Identifier, modifiedIdentifier, declarator.AsClause, declarator.Initializer, If(_syntax.Kind = SyntaxKind.ForEachBlock, LocalDeclarationKind.ForEach, LocalDeclarationKind.For)) Else Dim identifierName = TryCast(controlVariableSyntax, IdentifierNameSyntax) If identifierName IsNot Nothing Then Dim identifier = identifierName.Identifier If OptionInfer Then Dim result = LookupResult.GetInstance() ContainingBinder.Lookup(result, identifier.ValueText, 0, LookupOptions.AllMethodsOfAnyArity, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) ' If there was something found we do not create a new local of an inferred type. ' The only exception is if all symbols (should be one only, or the result is not good) are type symbols. ' It's perfectly legal to create a local named with the same name as the enclosing type. If Not (result.IsGoodOrAmbiguous AndAlso result.Symbols(0).Kind <> SymbolKind.NamedType AndAlso result.Symbols(0).Kind <> SymbolKind.TypeParameter) Then localVar = CreateLocalSymbol(identifier) End If result.Free() End If End If End If If localVar IsNot Nothing Then Return ImmutableArray.Create(localVar) End If Return ImmutableArray(Of LocalSymbol).Empty End Function Private Function CreateLocalSymbol(identifier As SyntaxToken) As LocalSymbol If _syntax.Kind = SyntaxKind.ForBlock Then Dim forStatementSyntax = DirectCast(_syntax.ForOrForEachStatement, ForStatementSyntax) Dim localVar = LocalSymbol.CreateInferredForFromTo(Me.ContainingMember, Me, identifier, forStatementSyntax.FromValue, forStatementSyntax.ToValue, forStatementSyntax.StepClause) Return localVar Else Dim forEachStatementSyntax = DirectCast(_syntax.ForOrForEachStatement, ForEachStatementSyntax) Dim localVar = LocalSymbol.CreateInferredForEach(Me.ContainingMember, Me, identifier, forEachStatementSyntax.Expression) Return localVar End If End Function End Class End Namespace
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSSourceModule.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.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("D9BF2800-E098-11d2-B554-00C04F68D4DB")] internal interface ICSSourceModule { // members not ported } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("D9BF2800-E098-11d2-B554-00C04F68D4DB")] internal interface ICSSourceModule { // members not ported } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = false; protected override bool IsAppropriateLiteralKind(LiteralExpressionSyntax literalExpression) => literalExpression.Kind() == SyntaxKind.StringLiteralExpression; protected override void AddSubStringTokens(LiteralExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) => subStringTokens.Add(literalExpression.Token); protected override bool IsVerbatim(LiteralExpressionSyntax literalExpression) => CSharpSyntaxFacts.Instance.IsVerbatimStringLiteral(literalExpression.Token); protected override LiteralExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append('@'); sb.Append(DoubleQuote); AddVerbatimStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } protected override LiteralExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append(DoubleQuote); AddRegularStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } private static SyntaxToken CreateStringToken(StringBuilder sb) => SyntaxFactory.Token( leading: default, SyntaxKind.StringLiteralToken, sb.ToString(), valueText: "", trailing: default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = false; protected override bool IsAppropriateLiteralKind(LiteralExpressionSyntax literalExpression) => literalExpression.Kind() == SyntaxKind.StringLiteralExpression; protected override void AddSubStringTokens(LiteralExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) => subStringTokens.Add(literalExpression.Token); protected override bool IsVerbatim(LiteralExpressionSyntax literalExpression) => CSharpSyntaxFacts.Instance.IsVerbatimStringLiteral(literalExpression.Token); protected override LiteralExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append('@'); sb.Append(DoubleQuote); AddVerbatimStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } protected override LiteralExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append(DoubleQuote); AddRegularStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } private static SyntaxToken CreateStringToken(StringBuilder sb) => SyntaxFactory.Token( leading: default, SyntaxKind.StringLiteralToken, sb.ToString(), valueText: "", trailing: default); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Test/SolutionExplorer/FakeAnalyzersCommandHandler.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.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Public Class FakeAnalyzersCommandHandler Implements IAnalyzersCommandHandler Public ReadOnly Property AnalyzerContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property AnalyzerFolderContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerFolderContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property DiagnosticContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.DiagnosticContextMenuController Get Return Nothing End Get End Property 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. Imports Microsoft.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Public Class FakeAnalyzersCommandHandler Implements IAnalyzersCommandHandler Public ReadOnly Property AnalyzerContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property AnalyzerFolderContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerFolderContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property DiagnosticContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.DiagnosticContextMenuController Get Return Nothing End Get End Property End Class
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/LiveShare/Impl/Client/ExternalAccess/VSTypeScript/VSTypeScriptRemoteLanguageServiceWorkspaceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.ExternalAccess.VSTypeScript { [Export(typeof(IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor))] internal sealed class VSTypeScriptRemoteLanguageServiceWorkspaceAccessor : IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptRemoteLanguageServiceWorkspaceAccessor(RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace; } CodeAnalysis.Workspace IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor.RemoteLanguageServiceWorkspace => _remoteLanguageServiceWorkspace; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.ExternalAccess.VSTypeScript { [Export(typeof(IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor))] internal sealed class VSTypeScriptRemoteLanguageServiceWorkspaceAccessor : IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptRemoteLanguageServiceWorkspaceAccessor(RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace; } CodeAnalysis.Workspace IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor.RemoteLanguageServiceWorkspace => _remoteLanguageServiceWorkspace; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBVariableInitializerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/IWorkspaceSettingsProviderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal interface IWorkspaceSettingsProviderFactory<TData> : ISettingsProviderFactory<TData>, IWorkspaceService { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal interface IWorkspaceSettingsProviderFactory<TData> : ISettingsProviderFactory<TData>, IWorkspaceService { } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileProviderMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal class MetadataAsSourceFileProviderMetadata : OrderableLanguageMetadata { public MetadataAsSourceFileProviderMetadata(IDictionary<string, object> data) : base(data) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal class MetadataAsSourceFileProviderMetadata : OrderableLanguageMetadata { public MetadataAsSourceFileProviderMetadata(IDictionary<string, object> data) : base(data) { } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class EditAndContinueDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private static readonly ImmutableArray<DiagnosticDescriptor> s_supportedDiagnostics = EditAndContinueDiagnosticDescriptors.GetDescriptors(); // Return known descriptors. This will not include module diagnostics reported on behalf of the debugger. public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => s_supportedDiagnostics; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) => false; // No syntax diagnostics produced by the EnC engine. public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; // do not load EnC service and its dependencies if the app is not running: var debuggingService = workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); if (debuggingService.CurrentDebuggingState == DebuggingState.Design) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return AnalyzeSemanticsImplAsync(workspace, document, cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] private static async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsImplAsync(Workspace workspace, Document designTimeDocument, CancellationToken cancellationToken) { var designTimeSolution = designTimeDocument.Project.Solution; var compileTimeSolution = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(designTimeSolution); var compileTimeDocument = await CompileTimeSolutionProvider.TryGetCompileTimeDocumentAsync(designTimeDocument, compileTimeSolution, cancellationToken).ConfigureAwait(false); if (compileTimeDocument == null) { return ImmutableArray<Diagnostic>.Empty; } // EnC services should never be called on a design-time solution. var proxy = new RemoteEditAndContinueServiceProxy(workspace); var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, filePath, cancellationToken) => { var trackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); return await trackingService.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken).ConfigureAwait(false); }); return await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, designTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class EditAndContinueDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private static readonly ImmutableArray<DiagnosticDescriptor> s_supportedDiagnostics = EditAndContinueDiagnosticDescriptors.GetDescriptors(); // Return known descriptors. This will not include module diagnostics reported on behalf of the debugger. public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => s_supportedDiagnostics; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) => false; // No syntax diagnostics produced by the EnC engine. public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document designTimeDocument, CancellationToken cancellationToken) { var workspace = designTimeDocument.Project.Solution.Workspace; if (workspace.Services.HostServices is not IMefHostExportProvider mefServices) { return ImmutableArray<Diagnostic>.Empty; } // avoid creating and synchronizing compile-time solution if the Hot Reload/EnC session is not active if (mefServices.GetExports<ManagedEditAndContinueLanguageService>().SingleOrDefault()?.Value.Service.IsSessionActive != true && mefServices.GetExports<ManagedHotReloadLanguageService>().SingleOrDefault()?.Value.Service.IsSessionActive != true) { return ImmutableArray<Diagnostic>.Empty; } var designTimeSolution = designTimeDocument.Project.Solution; var compileTimeSolution = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(designTimeSolution); var compileTimeDocument = await CompileTimeSolutionProvider.TryGetCompileTimeDocumentAsync(designTimeDocument, compileTimeSolution, cancellationToken).ConfigureAwait(false); if (compileTimeDocument == null) { return ImmutableArray<Diagnostic>.Empty; } // EnC services should never be called on a design-time solution. var proxy = new RemoteEditAndContinueServiceProxy(workspace); var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, filePath, cancellationToken) => { var trackingService = workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); return await trackingService.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken).ConfigureAwait(false); }); return await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, designTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/Implementation/EditAndContinue/ManagedEditAndContinueLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [Export(typeof(IEditAndContinueSolutionProvider))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService, IEditAndContinueSolutionProvider { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private RemoteDebuggingSessionProxy? _debuggingSession; private Solution? _pendingUpdatedSolution; public event Action<Solution>? SolutionCommitted; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedEditAndContinueDebuggerService> debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } private IDebuggingWorkspaceService GetDebuggingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); private IActiveStatementTrackingService GetActiveStatementTrackingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var workspace = _workspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService.Value, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public async Task ExitBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (_disabled) { return; } var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: false, cancellationToken).ConfigureAwait(false); GetActiveStatementTrackingService().EndTracking(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var committedSolution = Interlocked.Exchange(ref _pendingUpdatedSolution, null); Contract.ThrowIfNull(committedSolution); SolutionCommitted?.Invoke(committedSolution); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } try { await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } _pendingUpdatedSolution = null; try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) { var service = GetActiveStatementTrackingService(); return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken)); } /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); _pendingUpdatedSolution = solution; return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementTrackingService = GetActiveStatementTrackingService(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(ManagedEditAndContinueLanguageService))] [Export(typeof(IManagedEditAndContinueLanguageService))] [Export(typeof(IEditAndContinueSolutionProvider))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService, IEditAndContinueSolutionProvider { private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly EditAndContinueLanguageService _encService; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, Lazy<IManagedEditAndContinueDebuggerService> debuggerService) { _encService = new EditAndContinueLanguageService(workspaceProvider, diagnosticService, diagnosticUpdateSource); _debuggerService = debuggerService; } public EditAndContinueLanguageService Service => _encService; /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { if (flags.HasFlag(DebugSessionFlags.EditAndContinueDisabled)) { _encService.Disable(); return Task.CompletedTask; } return _encService.StartSessionAsync(_debuggerService.Value, cancellationToken).AsTask(); } public Task EnterBreakStateAsync(CancellationToken cancellationToken) => _encService.EnterBreakStateAsync(cancellationToken).AsTask(); public Task ExitBreakStateAsync(CancellationToken cancellationToken) => _encService.ExitBreakStateAsync(cancellationToken).AsTask(); public Task CommitUpdatesAsync(CancellationToken cancellationToken) => _encService.CommitUpdatesAsync(cancellationToken).AsTask(); public Task DiscardUpdatesAsync(CancellationToken cancellationToken) => _encService.DiscardUpdatesAsync(cancellationToken).AsTask(); public Task StopDebuggingAsync(CancellationToken cancellationToken) => _encService.EndSessionAsync(cancellationToken).AsTask(); public Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) => _encService.HasChangesAsync(sourceFilePath, cancellationToken).AsTask(); public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) => (await _encService.GetUpdatesAsync(trackActiveStatements: true, cancellationToken).ConfigureAwait(false)).updates; public Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) => _encService.GetCurrentActiveStatementPositionAsync(instruction, cancellationToken); public Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) => _encService.IsActiveStatementInExceptionRegionAsync(instruction, cancellationToken); public event Action<Solution> SolutionCommitted { add { _encService.SolutionCommitted += value; } remove { _encService.SolutionCommitted -= value; } } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/Implementation/EditAndContinue/ManagedHotReloadLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.VisualStudio.Debugger.Contracts.HotReload; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IEditAndContinueSolutionProvider))] [Export(typeof(IManagedHotReloadLanguageService))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedHotReloadLanguageService : IManagedHotReloadLanguageService, IEditAndContinueSolutionProvider { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly Lazy<IManagedHotReloadService> _hotReloadService; public DebuggerService(Lazy<IManagedHotReloadService> hotReloadService) { _hotReloadService = hotReloadService; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => _hotReloadService.Value.GetCapabilitiesAsync(cancellationToken).AsTask(); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly DebuggerService _debuggerService; private RemoteDebuggingSessionProxy? _debuggingSession; private Solution? _pendingUpdatedSolution; public event Action<Solution>? SolutionCommitted; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedHotReloadService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedHotReloadLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedHotReloadService> hotReloadService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = new DebuggerService(hotReloadService); _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } public async ValueTask StartSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); var workspace = _workspaceProvider.Value.Workspace; var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async ValueTask<ManagedHotReloadUpdates> GetUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray<ManagedHotReloadDiagnostic>.Empty); } try { var solution = GetCurrentCompileTimeSolution(); var (moduleUpdates, diagnosticData, rudeEdits, syntaxError) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, s_solutionActiveStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); var updates = moduleUpdates.Updates.SelectAsArray( update => new ManagedHotReloadUpdate(update.Module, update.ILDelta, update.MetadataDelta)); var diagnostics = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, syntaxError, cancellationToken).ConfigureAwait(false); _pendingUpdatedSolution = solution; return new ManagedHotReloadUpdates(updates, diagnostics); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.InternalError); // TODO: better error var diagnostic = new ManagedHotReloadDiagnostic( descriptor.Id, string.Format(descriptor.MessageFormat.ToString(), "", e.Message), ManagedHotReloadDiagnosticSeverity.Error, filePath: "", span: default); return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray.Create(diagnostic)); } } public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var committedSolution = Interlocked.Exchange(ref _pendingUpdatedSolution, null); Contract.ThrowIfNull(committedSolution); SolutionCommitted?.Invoke(committedSolution); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } try { await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } _pendingUpdatedSolution = null; try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { _disabled = true; } } public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = 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.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.VisualStudio.Debugger.Contracts.HotReload; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(ManagedHotReloadLanguageService))] [Export(typeof(IManagedHotReloadLanguageService))] [Export(typeof(IEditAndContinueSolutionProvider))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedHotReloadLanguageService : IManagedHotReloadLanguageService, IEditAndContinueSolutionProvider { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly Lazy<IManagedHotReloadService> _hotReloadService; public DebuggerService(Lazy<IManagedHotReloadService> hotReloadService) { _hotReloadService = hotReloadService; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => _hotReloadService.Value.GetCapabilitiesAsync(cancellationToken).AsTask(); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } private readonly EditAndContinueLanguageService _encService; private readonly DebuggerService _debuggerService; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedHotReloadService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedHotReloadLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, Lazy<IManagedHotReloadService> hotReloadService) { _encService = new EditAndContinueLanguageService(workspaceProvider, diagnosticService, diagnosticUpdateSource); _debuggerService = new DebuggerService(hotReloadService); } public EditAndContinueLanguageService Service => _encService; public ValueTask StartSessionAsync(CancellationToken cancellationToken) => _encService.StartSessionAsync(_debuggerService, cancellationToken); public async ValueTask<ManagedHotReloadUpdates> GetUpdatesAsync(CancellationToken cancellationToken) { var (moduleUpdates, diagnosticData, rudeEdits, syntaxError, solution) = await _encService.GetUpdatesAsync(trackActiveStatements: false, cancellationToken).ConfigureAwait(false); if (solution == null) { return new ManagedHotReloadUpdates(ImmutableArray<ManagedHotReloadUpdate>.Empty, ImmutableArray<ManagedHotReloadDiagnostic>.Empty); } var updates = moduleUpdates.Updates.SelectAsArray( update => new ManagedHotReloadUpdate(update.Module, update.ILDelta, update.MetadataDelta)); var diagnostics = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, syntaxError, cancellationToken).ConfigureAwait(false); return new ManagedHotReloadUpdates(updates, diagnostics); } public ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) => _encService.CommitUpdatesAsync(cancellationToken); public ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) => _encService.DiscardUpdatesAsync(cancellationToken); public ValueTask EndSessionAsync(CancellationToken cancellationToken) => _encService.EndSessionAsync(cancellationToken); public event Action<Solution> SolutionCommitted { add { _encService.SolutionCommitted += value; } remove { _encService.SolutionCommitted -= value; } } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateChanged(inBreakState: true, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState( DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; session.BreakStateChanged(inBreakState: false, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(1204, "https://github.com/dotnet/roslyn/issues/1204")] [WorkItem(1371694, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371694")] public async Task Project_Add() { var sourceA1 = "class A { void M() { System.Console.WriteLine(1); } }"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int G() => 1; }"; var sourceB3 = "class B { int F() => 2; }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA1); var sourceFileB = dir.CreateFile("b.cs").WriteAllText(sourceB1); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1 }); var documentA1 = solution.Projects.Single().Documents.Single(); var mvidA = EmitAndLoadLibraryToDebuggee(sourceA1, sourceFilePath: sourceFileA.Path, assemblyName: "A"); var mvidB = EmitAndLoadLibraryToDebuggee(sourceB1, sourceFilePath: sourceFileB.Path, assemblyName: "B"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // An active statement may be present in the added file since the file exists in the PDB: var activeLineSpanA1 = SourceText.From(sourceA1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceA1, "System.Console.WriteLine(1);")); var activeLineSpanB1 = SourceText.From(sourceB1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceB1, "1")); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidA, token: 0x06000001, version: 1), ilOffset: 1), sourceFileA.Path, activeLineSpanA1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate), new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidB, token: 0x06000001, version: 1), ilOffset: 1), sourceFileB.Path, activeLineSpanB1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate)); EnterBreakState(debuggingSession, activeStatements); // add project that matches assembly B and update the document: var documentB2 = solution. AddProject("B", "B", LanguageNames.CSharp). AddDocument("b.cs", SourceText.From(sourceB2, Encoding.UTF8, SourceHashAlgorithm.Sha256), filePath: sourceFileB.Path); solution = documentB2.Project.Solution; // TODO: https://github.com/dotnet/roslyn/issues/1204 // Should return span in document B since the document content matches the PDB. var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentA1.Id, documentB2.Id), CancellationToken.None); AssertEx.Equal(new[] { "<empty>", "(0,21)-(0,22)" }, baseSpans.Select(spans => spans.IsEmpty ? "<empty>" : string.Join(",", spans.Select(s => s.LineSpan.ToString())))); var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(1, activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); Assert.Equal(activeLineSpanB1, await debuggingSession.GetCurrentActiveStatementPositionAsync(documentB2.Project.Solution, (_, _, _) => new(trackedActiveSpans), activeStatements[1].ActiveInstruction, CancellationToken.None)); var diagnostics = await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 //AssertEx.Equal( // new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, // diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(diagnostics); // update document with a valid change: solution = solution.WithDocumentText(documentB2.Id, SourceText.From(sourceB3, Encoding.UTF8, SourceHashAlgorithm.Sha256)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); // TODO: https://github.com/dotnet/roslyn/issues/1204 // verify valid update Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(debuggingSession); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities_SynthesizedNewType() { var source1 = "class C { void M() { } }"; var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var project = solution.Projects.Single(); solution = solution.WithProjectParseOptions(project.Id, new CSharpParseOptions(LanguageVersion.CSharp10)); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that doesn't allow creating new types _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // They are reported as emit diagnostics var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1007: {FeaturesResources.ChangesRequiredSynthesizedType}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 3 : 2)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(54347, "https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { var markedSource1 = @" class C { int F() { try { return 0; } catch { <AS:0>return 1;</AS:0> } } } "; var markedSource2 = @" class C { int F() { try { return 0; } catch { <AS:0>return 2;</AS:0> } } } "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); var moduleId = EmitLibrary(source1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (rude edit) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); // undo the change solution = solution.WithDocumentText(document.Id, SourceText.From(source1, Encoding.UTF8)); document = solution.GetDocument(document.Id); ExitBreakState(debuggingSession, ImmutableArray.Create(document.Id)); // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit (Hot Reload change): (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is not produced for F v2 -> F v3. If G ever returned to F it will be remapped from F v1 -> F v2, /// where F v2 is considered stale code. This is consistent with the semantic of Hot Reload: Hot Reloaded changes do not have /// an effect until the method is called again. In this case the method is not called, it it returned into hence the stale /// version executes. /// 3) Break and apply EnC edit. This edit is to F v3 (Hot Reload) of the method. We will produce remapping F v3 -> v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // the regions remain unchanged AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsStale | ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore and since F v1 is followed by F v3 (hot-reload) it is now stale })); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, new LinePositionSpan(new(4,41), new(4,42)), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Stale active statement region is gone. AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (3,41)-(3,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionG1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000002, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionG1, CancellationToken.None); Assert.Equal(expectedSpanG1, span); // Active statement in F has been deleted: var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Null(span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) // active statement in F has been deleted }, spans); ExitBreakState(debuggingSession); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateChanged(inBreakState: true, out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { // See https://github.com/dotnet/sdk/blob/main/src/BuiltInTools/dotnet-watch/HotReload/CompilationHandler.cs#L125 var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid update: solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); // Rude edit: solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error (not reported in diagnostics): solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid change solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); // Rude edit result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error is reported in the diagnostics: solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Equal(1, result.diagnostics.Length); Assert.Empty(result.updates); hotReload.EndSession(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateChanged(inBreakState: true, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState( DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; session.BreakStateChanged(inBreakState: false, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); debuggingSession.DiscardSolutionUpdate(); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatusEx.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(1204, "https://github.com/dotnet/roslyn/issues/1204")] [WorkItem(1371694, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371694")] public async Task Project_Add() { var sourceA1 = "class A { void M() { System.Console.WriteLine(1); } }"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int G() => 1; }"; var sourceB3 = "class B { int F() => 2; }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA1); var sourceFileB = dir.CreateFile("b.cs").WriteAllText(sourceB1); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1 }); var documentA1 = solution.Projects.Single().Documents.Single(); var mvidA = EmitAndLoadLibraryToDebuggee(sourceA1, sourceFilePath: sourceFileA.Path, assemblyName: "A"); var mvidB = EmitAndLoadLibraryToDebuggee(sourceB1, sourceFilePath: sourceFileB.Path, assemblyName: "B"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // An active statement may be present in the added file since the file exists in the PDB: var activeLineSpanA1 = SourceText.From(sourceA1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceA1, "System.Console.WriteLine(1);")); var activeLineSpanB1 = SourceText.From(sourceB1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceB1, "1")); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidA, token: 0x06000001, version: 1), ilOffset: 1), sourceFileA.Path, activeLineSpanA1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate), new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidB, token: 0x06000001, version: 1), ilOffset: 1), sourceFileB.Path, activeLineSpanB1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate)); EnterBreakState(debuggingSession, activeStatements); // add project that matches assembly B and update the document: var documentB2 = solution. AddProject("B", "B", LanguageNames.CSharp). AddDocument("b.cs", SourceText.From(sourceB2, Encoding.UTF8, SourceHashAlgorithm.Sha256), filePath: sourceFileB.Path); solution = documentB2.Project.Solution; // TODO: https://github.com/dotnet/roslyn/issues/1204 // Should return span in document B since the document content matches the PDB. var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentA1.Id, documentB2.Id), CancellationToken.None); AssertEx.Equal(new[] { "<empty>", "(0,21)-(0,22)" }, baseSpans.Select(spans => spans.IsEmpty ? "<empty>" : string.Join(",", spans.Select(s => s.LineSpan.ToString())))); var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(1, activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); Assert.Equal(activeLineSpanB1, await debuggingSession.GetCurrentActiveStatementPositionAsync(documentB2.Project.Solution, (_, _, _) => new(trackedActiveSpans), activeStatements[1].ActiveInstruction, CancellationToken.None)); var diagnostics = await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 //AssertEx.Equal( // new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, // diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(diagnostics); // update document with a valid change: solution = solution.WithDocumentText(documentB2.Id, SourceText.From(sourceB3, Encoding.UTF8, SourceHashAlgorithm.Sha256)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); // TODO: https://github.com/dotnet/roslyn/issues/1204 // verify valid update Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(debuggingSession); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities_SynthesizedNewType() { var source1 = "class C { void M() { } }"; var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var project = solution.Projects.Single(); solution = solution.WithProjectParseOptions(project.Id, new CSharpParseOptions(LanguageVersion.CSharp10)); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that doesn't allow creating new types _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // They are reported as emit diagnostics var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1007: {FeaturesResources.ChangesRequiredSynthesizedType}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); debuggingSession.DiscardSolutionUpdate(); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); debuggingSession.DiscardSolutionUpdate(); } if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 3 : 2)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); debuggingSession.DiscardSolutionUpdate(); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(54347, "https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { var markedSource1 = @" class C { int F() { try { return 0; } catch { <AS:0>return 1;</AS:0> } } } "; var markedSource2 = @" class C { int F() { try { return 0; } catch { <AS:0>return 2;</AS:0> } } } "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); var moduleId = EmitLibrary(source1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (rude edit) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatusEx.RestartRequired, updates.Status); // undo the change solution = solution.WithDocumentText(document.Id, SourceText.From(source1, Encoding.UTF8)); document = solution.GetDocument(document.Id); ExitBreakState(debuggingSession, ImmutableArray.Create(document.Id)); // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit (Hot Reload change): (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is not produced for F v2 -> F v3. If G ever returned to F it will be remapped from F v1 -> F v2, /// where F v2 is considered stale code. This is consistent with the semantic of Hot Reload: Hot Reloaded changes do not have /// an effect until the method is called again. In this case the method is not called, it it returned into hence the stale /// version executes. /// 3) Break and apply EnC edit. This edit is to F v3 (Hot Reload) of the method. We will produce remapping F v3 -> v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // the regions remain unchanged AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsStale | ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore and since F v1 is followed by F v3 (hot-reload) it is now stale })); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, new LinePositionSpan(new(4,41), new(4,42)), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Stale active statement region is gone. AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (3,41)-(3,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionG1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000002, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionG1, CancellationToken.None); Assert.Equal(expectedSpanG1, span); // Active statement in F has been deleted: var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Null(span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) // active statement in F has been deleted }, spans); ExitBreakState(debuggingSession); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); encService.DiscardSolutionUpdate(sessionId); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateChanged(inBreakState: true, out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { // See https://github.com/dotnet/sdk/blob/main/src/BuiltInTools/dotnet-watch/HotReload/CompilationHandler.cs#L125 var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid update: solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); // Rude edit: solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error (not reported in diagnostics): solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid change solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); // Rude edit result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error is reported in the diagnostics: solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Equal(1, result.diagnostics.Length); Assert.Empty(result.updates); hotReload.EndSession(); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Test/EditAndContinue/RemoteEditAndContinueServiceTests.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 enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEncServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new MockEditAndContinueWorkspaceService(); } private static string Inspect(DiagnosticData d) => $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEncServiceFactory)); } using var localWorkspace = new TestWorkspace(composition: localComposition); var globalOptions = localWorkspace.GetService<IGlobalOptionService>(); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateChanged mockEncService.BreakStateChangesImpl = (bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => { Assert.True(inBreakState); documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateChangedAsync(mockDiagnosticService, inBreakState: true, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var syntaxError = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "syntax error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits, syntaxError); }; var (updates, _, _, syntaxErrorData) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal($"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "syntax error")}", Inspect(syntaxErrorData!)); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => Inspect(update.GetPushDiagnostics(globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode).Single()))); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
// Licensed to the .NET Foundation under one or more 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 enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { private static string Inspect(DiagnosticData d) => $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEditAndContinueWorkspaceService)); } using var localWorkspace = new TestWorkspace(composition: localComposition); var globalOptions = localWorkspace.GetService<IGlobalOptionService>(); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEditAndContinueWorkspaceService) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateChanged mockEncService.BreakStateChangesImpl = (bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => { Assert.True(inBreakState); documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateChangedAsync(mockDiagnosticService, inBreakState: true, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var syntaxError = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "syntax error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits, syntaxError); }; var (updates, _, _, syntaxErrorData) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal($"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "syntax error")}", Inspect(syntaxErrorData!)); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => Inspect(update.GetPushDiagnostics(globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode).Single()))); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/TestUtilities/EditAndContinue/MockEditAndContinueWorkspaceService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<TArg1>(out TArg1 arg); internal delegate void ActionOut<TArg1, TArg2>(TArg1 arg1, out TArg2 arg2); internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<bool, ImmutableArray<DocumentId>>? BreakStateChangesImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateChangesImpl?.Invoke(inBreakState, out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<TArg1>(out TArg1 arg); internal delegate void ActionOut<TArg1, TArg2>(TArg1 arg1, out TArg2 arg2); [ExportWorkspaceService(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<bool, ImmutableArray<DocumentId>>? BreakStateChangesImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEditAndContinueWorkspaceService() { } public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateChangesImpl?.Invoke(inBreakState, out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateChanged(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits, solutionUpdate.SyntaxError); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // document is in a project that's been added to the solution continue; } var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // TODO: https://github.com/dotnet/roslyn/issues/1204 // Enumerate all documents of the new project. return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // TODO: https://github.com/dotnet/roslyn/issues/1204 // project has been added - it may have active statements if the project was unloaded when debugging session started but the sources // correspond to the PDB. return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, oldProject, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var oldProject = LastCommittedSolution.GetProject(projectId); // TODO: https://github.com/dotnet/roslyn/issues/1204 // oldProject == null ==> project has been added - it may have active statements if the project was unloaded when debugging session started but the sources // correspond to the PDB. var id = (oldProject != null) ? await GetChangedDocumentContainingUnmappedActiveStatementAsync( activeStatementsMap, LastCommittedSolution, oldProject, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false) : null; Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project oldProject, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { Debug.Assert(oldProject.Id == newProject.Id); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; map["Capabilities"] = (int)editSessionData.Capabilities; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); if (Interlocked.Exchange(ref _pendingUpdate, null) != null) { throw new InvalidOperationException($"Pending update has not been committed or discarded."); } } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: if (previousPendingUpdate != null) { throw new InvalidOperationException($"Previous update has not been committed or discarded."); } } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); if (pendingUpdate == null) { throw new InvalidOperationException($"No pending update."); } return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateChanged(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits, solutionUpdate.SyntaxError); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // document is in a project that's been added to the solution continue; } var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // TODO: https://github.com/dotnet/roslyn/issues/1204 // Enumerate all documents of the new project. return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // TODO: https://github.com/dotnet/roslyn/issues/1204 // project has been added - it may have active statements if the project was unloaded when debugging session started but the sources // correspond to the PDB. return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, oldProject, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var oldProject = LastCommittedSolution.GetProject(projectId); // TODO: https://github.com/dotnet/roslyn/issues/1204 // oldProject == null ==> project has been added - it may have active statements if the project was unloaded when debugging session started but the sources // correspond to the PDB. var id = (oldProject != null) ? await GetChangedDocumentContainingUnmappedActiveStatementAsync( activeStatementsMap, LastCommittedSolution, oldProject, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false) : null; Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project oldProject, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { Debug.Assert(oldProject.Id == newProject.Id); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldProject, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; map["Capabilities"] = (int)editSessionData.Capabilities; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateChanged(inBreakState, out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
// Licensed to the .NET Foundation under one or more 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.Emit; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> [ExportWorkspaceService(typeof(IEditAndContinueWorkspaceService)), Shared] internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateChanged(inBreakState, out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether updates have been made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null). /// </summary> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/EditAndContinue/EditSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// The compiler has various scenarios that will cause it to synthesize things that might not be covered /// by existing rude edits, but we still need to ensure the runtime supports them before we proceed. /// </summary> private async Task<Diagnostic?> GetUnsupportedChangesDiagnosticAsync(EmitDifferenceResult emitResult, CancellationToken cancellationToken) { Debug.Assert(emitResult.Success); Debug.Assert(emitResult.Baseline is not null); var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // If the runtime doesn't support adding new types then we expect every row number for any type that is // emitted will be less than or equal to the number of rows in the original metadata. var highestEmittedTypeDefRow = emitResult.ChangedTypes.Max(t => MetadataTokens.GetRowNumber(t)); var highestExistingTypeDefRow = emitResult.Baseline.OriginalMetadata.GetMetadataReader().GetTableRowCount(TableIndex.TypeDef); if (highestEmittedTypeDefRow > highestExistingTypeDefRow) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); return Diagnostic.Create(descriptor, Location.None); } } return null; } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); // TODO (https://github.com/dotnet/roslyn/issues/1204): // // When debugging session is started some projects might not have been loaded to the workspace yet (may be explicitly unloaded by the user). // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // We can allow project to be added by including all its documents here. // When we analyze these documents later on we'll check if they match the PDB. // If so we can add them to the committed solution and detect further changes. // It might be more efficient though to track added projects separately. return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(Project oldProject, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { Debug.Assert(oldProject.Id == newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); Diagnostic? syntaxError = null; var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { // only remember the first syntax error we encounter: syntaxError ??= changedDocumentAnalyses.FirstOrDefault(a => a.SyntaxError != null)?.SyntaxError; isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); if (unsupportedChangesDiagnostic is not null) { diagnostics.Add((newProject.Id, ImmutableArray.Create(unsupportedChangesDiagnostic))); isBlocked = true; } else { var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } // log capabilities for edit sessions with changes or reported errors: if (isBlocked || deltas.Count > 0) { Telemetry.LogRuntimeCapabilities(await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false)); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable(), syntaxError) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable(), syntaxError); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } Debug.Assert(!oldActiveStatement.IsStale); // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); // The up-to-date flag is copied when new active statement is created from the corresponding old one. Debug.Assert(oldActiveStatement.IsMethodUpToDate == newActiveStatement.IsMethodUpToDate); if (oldActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } else if (!isExceptionRegion) { // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. // // That said, we still add a non-remappable region for this active statement, so that we know in future sessions // that this active statement existed and its span has not changed. We don't report these regions to the debugger, // but we use them to map active statement spans to the baseline snapshots of following edit sessions. nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta: 0, isExceptionRegion: false))); } } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we might have a previous non-remappable span mapping that needs to be brought forward to the new snapshot. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } // Update previously calculated non-remappable region mappings. // These map to the old snapshot and we need them to map to the new snapshot, which will be the baseline for the next session. if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { // Skip non-remappable regions that belong to method instances that are from a different module. if (methodInstance.Module != moduleId) { continue; } // Skip no longer active methods - all active statements in these method instances have been remapped to newer versions. // New active statement can't appear in a stale method instance since such instance can't be invoked. if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// The compiler has various scenarios that will cause it to synthesize things that might not be covered /// by existing rude edits, but we still need to ensure the runtime supports them before we proceed. /// </summary> private async Task<Diagnostic?> GetUnsupportedChangesDiagnosticAsync(EmitDifferenceResult emitResult, CancellationToken cancellationToken) { Debug.Assert(emitResult.Success); Debug.Assert(emitResult.Baseline is not null); var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // If the runtime doesn't support adding new types then we expect every row number for any type that is // emitted will be less than or equal to the number of rows in the original metadata. var highestEmittedTypeDefRow = emitResult.ChangedTypes.Max(t => MetadataTokens.GetRowNumber(t)); var highestExistingTypeDefRow = emitResult.Baseline.OriginalMetadata.GetMetadataReader().GetTableRowCount(TableIndex.TypeDef); if (highestEmittedTypeDefRow > highestExistingTypeDefRow) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); return Diagnostic.Create(descriptor, Location.None); } } return null; } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); // TODO (https://github.com/dotnet/roslyn/issues/1204): // // When debugging session is started some projects might not have been loaded to the workspace yet (may be explicitly unloaded by the user). // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // We can allow project to be added by including all its documents here. // When we analyze these documents later on we'll check if they match the PDB. // If so we can add them to the committed solution and detect further changes. // It might be more efficient though to track added projects separately. return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(Project oldProject, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { Debug.Assert(oldProject.Id == newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); Diagnostic? syntaxError = null; var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; var hasEmitErrors = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { // only remember the first syntax error we encounter: syntaxError ??= changedDocumentAnalyses.FirstOrDefault(a => a.SyntaxError != null)?.SyntaxError; isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); if (unsupportedChangesDiagnostic is not null) { diagnostics.Add((newProject.Id, ImmutableArray.Create(unsupportedChangesDiagnostic))); isBlocked = true; } else { var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } } else { // error isBlocked = hasEmitErrors = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } // log capabilities for edit sessions with changes or reported errors: if (isBlocked || deltas.Count > 0) { Telemetry.LogRuntimeCapabilities(await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false)); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable(), syntaxError, hasEmitErrors) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable(), syntaxError); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } Debug.Assert(!oldActiveStatement.IsStale); // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); // The up-to-date flag is copied when new active statement is created from the corresponding old one. Debug.Assert(oldActiveStatement.IsMethodUpToDate == newActiveStatement.IsMethodUpToDate); if (oldActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } else if (!isExceptionRegion) { // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. // // That said, we still add a non-remappable region for this active statement, so that we know in future sessions // that this active statement existed and its span has not changed. We don't report these regions to the debugger, // but we use them to map active statement spans to the baseline snapshots of following edit sessions. nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta: 0, isExceptionRegion: false))); } } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we might have a previous non-remappable span mapping that needs to be brought forward to the new snapshot. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } // Update previously calculated non-remappable region mappings. // These map to the old snapshot and we need them to map to the new snapshot, which will be the baseline for the next session. if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { // Skip non-remappable regions that belong to method instances that are from a different module. if (methodInstance.Module != moduleId) { continue; } // Skip no longer active methods - all active statements in these method instances have been remapped to newer versions. // New active statement can't appear in a stale method instance since such instance can't be invoked. if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits, DiagnosticData? syntaxError)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; DiagnosticData? syntaxError; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; syntaxError = results.GetSyntaxErrorData(solution); } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; syntaxError = result.Value.SyntaxError; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; syntaxError = null; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits, syntaxError); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.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.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits, DiagnosticData? syntaxError)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; DiagnosticData? syntaxError; try { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; syntaxError = results.GetSyntaxErrorData(solution); } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; syntaxError = result.Value.SyntaxError; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatusEx.RestartRequired, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; syntaxError = null; } } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.InternalError); var diagnostic = Diagnostic.Create( descriptor, Location.None, string.Format(descriptor.MessageFormat.ToString(), "", e.Message)); diagnosticData = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options)); rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatusEx.RestartRequired, ImmutableArray<ManagedModuleUpdate>.Empty); syntaxError = null; } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits, syntaxError); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/EditAndContinue/SolutionUpdate.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.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public readonly Diagnostic? SyntaxError; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits, Diagnostic? syntaxError) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; SyntaxError = syntaxError; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits, Diagnostic? syntaxError) => new( new(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits, syntaxError); } }
// Licensed to the .NET Foundation under one or more 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.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public readonly Diagnostic? SyntaxError; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits, Diagnostic? syntaxError) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; SyntaxError = syntaxError; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits, Diagnostic? syntaxError, bool hasEmitErrors) => new( new(syntaxError != null || hasEmitErrors ? ManagedModuleUpdateStatusEx.Blocked : ManagedModuleUpdateStatusEx.RestartRequired, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits, syntaxError); } }
1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/Diagnostics/DefaultDiagnosticAnalyzerService.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; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Shared] [ExportIncrementalAnalyzerProvider(WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: null)] internal partial class DefaultDiagnosticAnalyzerService : IIncrementalAnalyzerProvider, IDiagnosticUpdateSource { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticAnalyzerService( IDiagnosticUpdateSourceRegistrationService registrationService) { _analyzerInfoCache = new DiagnosticAnalyzerInfoCache(); registrationService.Register(this); } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new DefaultDiagnosticIncrementalAnalyzer(this, workspace); public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } // this only support push model, pull model will be provided by DiagnosticService by caching everything this one pushed public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { // pull model not supported return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); } internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs state) => DiagnosticsUpdated?.Invoke(this, state); private class DefaultDiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly DefaultDiagnosticAnalyzerService _service; private readonly Workspace _workspace; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; public DefaultDiagnosticIncrementalAnalyzer(DefaultDiagnosticAnalyzerService service, Workspace workspace) { _service = service; _workspace = workspace; _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(service._analyzerInfoCache); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { if (e.Option == InternalRuntimeDiagnosticOptions.Syntax || e.Option == InternalRuntimeDiagnosticOptions.Semantic || e.Option == InternalRuntimeDiagnosticOptions.ScriptSemantic) { return true; } return false; } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(document, cancellationToken); public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(textDocument, cancellationToken); private async Task AnalyzeSyntaxOrNonSourceDocumentAsync(TextDocument textDocument, CancellationToken cancellationToken) { Debug.Assert(textDocument.Project.Solution.Workspace == _workspace); // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(textDocument.Id) || !_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Syntax)) { return; } await AnalyzeForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false); } public async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { Debug.Assert(document.Project.Solution.Workspace == _workspace); if (!IsSemanticAnalysisOn()) { return; } await AnalyzeForKindAsync(document, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false); bool IsSemanticAnalysisOn() { // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(document.Id)) { return false; } if (_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Semantic)) { return true; } return _workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.ScriptSemantic) && document.SourceCodeKind == SourceCodeKind.Script; } } private async Task AnalyzeForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var diagnosticData = await GetDiagnosticsAsync(document, kind, cancellationToken).ConfigureAwait(false); _service.RaiseDiagnosticsUpdated( DiagnosticsUpdatedArgs.DiagnosticsCreated(new DefaultUpdateArgsId(_workspace.Kind, kind, document.Id), _workspace, document.Project.Solution, document.Project.Id, document.Id, diagnosticData)); } /// <summary> /// Get diagnostics for the given document. /// /// This is a simple API to get all diagnostics for the given document. /// /// The intended audience for this API is for ones that pefer simplicity over performance such as document that belong to misc project. /// this doesn't cache nor use cache for anything. it will re-caculate new diagnostics every time for the given document. /// it will not persist any data on disk nor use OOP to calculate the data. /// /// This should never be used when performance is a big concern. for such context, use much complex API from IDiagnosticAnalyzerService /// that provide all kinds of knobs/cache/persistency/OOP to get better perf over simplicity. /// </summary> private async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) return ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document)); var project = document.Project; var analyzers = GetAnalyzers(project.Solution.State.Analyzers, project); if (analyzers.IsEmpty) return ImmutableArray<DiagnosticData>.Empty; var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync( project, analyzers, includeSuppressedDiagnostics: false, cancellationToken).ConfigureAwait(false); var analysisScope = new DocumentAnalysisScope(document, span: null, analyzers, kind); var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true); using var _ = ArrayBuilder<DiagnosticData>.GetInstance(out var builder); foreach (var analyzer in analyzers) builder.AddRange(await executor.ComputeDiagnosticsAsync(analyzer, cancellationToken).ConfigureAwait(false)); return builder.ToImmutable(); } private static ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(HostDiagnosticAnalyzers hostAnalyzers, Project project) { // C# or VB document that supports compiler var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null) { return ImmutableArray.Create(compilerAnalyzer); } // document that doesn't support compiler diagnostics such as FSharp or TypeScript return hostAnalyzers.CreateDiagnosticAnalyzersPerReference(project).Values.SelectMany(v => v).ToImmutableArrayOrEmpty(); } public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // a file is removed from a solution // // here syntax and semantic indicates type of errors not where it is originated from. // Option.Semantic or Option.ScriptSemantic indicates what kind of document we will produce semantic errors from. // Option.Semantic == true means we will generate semantic errors for all document type // Option.ScriptSemantic == true means we will generate semantic errors only for script document type // both of them at the end generates semantic errors RaiseEmptyDiagnosticUpdated(AnalysisKind.Syntax, documentId); RaiseEmptyDiagnosticUpdated(AnalysisKind.Semantic, documentId); return Task.CompletedTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(document.Id, cancellationToken); } public Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(textDocument.Id, cancellationToken); } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => DocumentResetAsync(document, cancellationToken); public Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken) => NonSourceDocumentResetAsync(textDocument, cancellationToken); private void RaiseEmptyDiagnosticUpdated(AnalysisKind kind, DocumentId documentId) { _service.RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs.DiagnosticsRemoved( new DefaultUpdateArgsId(_workspace.Kind, kind, documentId), _workspace, null, documentId.ProjectId, documentId)); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken) => Task.CompletedTask; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask; private class DefaultUpdateArgsId : BuildToolId.Base<int, DocumentId>, ISupportLiveUpdate { private readonly string _workspaceKind; public DefaultUpdateArgsId(string workspaceKind, AnalysisKind kind, DocumentId documentId) : base((int)kind, documentId) => _workspaceKind = workspaceKind; public override string BuildTool => PredefinedBuildTools.Live; public override bool Equals(object obj) { if (obj is not DefaultUpdateArgsId other) { return false; } return _workspaceKind == other._workspaceKind && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_workspaceKind.GetHashCode(), base.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Shared] [ExportIncrementalAnalyzerProvider(WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: null)] internal partial class DefaultDiagnosticAnalyzerService : IIncrementalAnalyzerProvider, IDiagnosticUpdateSource { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticAnalyzerService( IDiagnosticUpdateSourceRegistrationService registrationService) { _analyzerInfoCache = new DiagnosticAnalyzerInfoCache(); registrationService.Register(this); } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new DefaultDiagnosticIncrementalAnalyzer(this, workspace); public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } // this only support push model, pull model will be provided by DiagnosticService by caching everything this one pushed public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { // pull model not supported return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); } internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs state) => DiagnosticsUpdated?.Invoke(this, state); private class DefaultDiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly DefaultDiagnosticAnalyzerService _service; private readonly Workspace _workspace; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; public DefaultDiagnosticIncrementalAnalyzer(DefaultDiagnosticAnalyzerService service, Workspace workspace) { _service = service; _workspace = workspace; _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(service._analyzerInfoCache); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { if (e.Option == InternalRuntimeDiagnosticOptions.Syntax || e.Option == InternalRuntimeDiagnosticOptions.Semantic || e.Option == InternalRuntimeDiagnosticOptions.ScriptSemantic) { return true; } return false; } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(document, cancellationToken); public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeSyntaxOrNonSourceDocumentAsync(textDocument, cancellationToken); private async Task AnalyzeSyntaxOrNonSourceDocumentAsync(TextDocument textDocument, CancellationToken cancellationToken) { Debug.Assert(textDocument.Project.Solution.Workspace == _workspace); // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(textDocument.Id) || !_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Syntax)) { return; } await AnalyzeForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false); } public async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { Debug.Assert(document.Project.Solution.Workspace == _workspace); if (!IsSemanticAnalysisOn()) { return; } await AnalyzeForKindAsync(document, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false); bool IsSemanticAnalysisOn() { // right now, there is no way to observe diagnostics for closed file. if (!_workspace.IsDocumentOpen(document.Id)) { return false; } if (_workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.Semantic)) { return true; } return _workspace.Options.GetOption(InternalRuntimeDiagnosticOptions.ScriptSemantic) && document.SourceCodeKind == SourceCodeKind.Script; } } private async Task AnalyzeForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var diagnosticData = await GetDiagnosticsAsync(document, kind, cancellationToken).ConfigureAwait(false); _service.RaiseDiagnosticsUpdated( DiagnosticsUpdatedArgs.DiagnosticsCreated(new DefaultUpdateArgsId(_workspace.Kind, kind, document.Id), _workspace, document.Project.Solution, document.Project.Id, document.Id, diagnosticData)); } /// <summary> /// Get diagnostics for the given document. /// /// This is a simple API to get all diagnostics for the given document. /// /// The intended audience for this API is for ones that pefer simplicity over performance such as document that belong to misc project. /// this doesn't cache nor use cache for anything. it will re-caculate new diagnostics every time for the given document. /// it will not persist any data on disk nor use OOP to calculate the data. /// /// This should never be used when performance is a big concern. for such context, use much complex API from IDiagnosticAnalyzerService /// that provide all kinds of knobs/cache/persistency/OOP to get better perf over simplicity. /// </summary> private async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) return ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document)); var project = document.Project; var analyzers = GetAnalyzers(project.Solution.State.Analyzers, project); if (analyzers.IsEmpty) return ImmutableArray<DiagnosticData>.Empty; var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync( project, analyzers, includeSuppressedDiagnostics: false, cancellationToken).ConfigureAwait(false); var analysisScope = new DocumentAnalysisScope(document, span: null, analyzers, kind); var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true); using var _ = ArrayBuilder<DiagnosticData>.GetInstance(out var builder); foreach (var analyzer in analyzers) builder.AddRange(await executor.ComputeDiagnosticsAsync(analyzer, cancellationToken).ConfigureAwait(false)); return builder.ToImmutable(); } private static ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(HostDiagnosticAnalyzers hostAnalyzers, Project project) { // C# or VB document that supports compiler var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null) { return ImmutableArray.Create(compilerAnalyzer); } // document that doesn't support compiler diagnostics such as FSharp or TypeScript return hostAnalyzers.CreateDiagnosticAnalyzersPerReference(project).Values.SelectMany(v => v).ToImmutableArrayOrEmpty(); } public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // a file is removed from a solution // // here syntax and semantic indicates type of errors not where it is originated from. // Option.Semantic or Option.ScriptSemantic indicates what kind of document we will produce semantic errors from. // Option.Semantic == true means we will generate semantic errors for all document type // Option.ScriptSemantic == true means we will generate semantic errors only for script document type // both of them at the end generates semantic errors RaiseEmptyDiagnosticUpdated(AnalysisKind.Syntax, documentId); RaiseEmptyDiagnosticUpdated(AnalysisKind.Semantic, documentId); return Task.CompletedTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(document.Id, cancellationToken); } public Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken) { // no closed file diagnostic and file is not opened, remove any existing diagnostics return RemoveDocumentAsync(textDocument.Id, cancellationToken); } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => DocumentResetAsync(document, cancellationToken); public Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken) => NonSourceDocumentResetAsync(textDocument, cancellationToken); private void RaiseEmptyDiagnosticUpdated(AnalysisKind kind, DocumentId documentId) { _service.RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs.DiagnosticsRemoved( new DefaultUpdateArgsId(_workspace.Kind, kind, documentId), _workspace, null, documentId.ProjectId, documentId)); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken) => Task.CompletedTask; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) => Task.CompletedTask; private class DefaultUpdateArgsId : BuildToolId.Base<int, DocumentId>, ISupportLiveUpdate { private readonly string _workspaceKind; public DefaultUpdateArgsId(string workspaceKind, AnalysisKind kind, DocumentId documentId) : base((int)kind, documentId) => _workspaceKind = workspaceKind; public override string BuildTool => PredefinedBuildTools.Live; public override bool Equals(object obj) { if (obj is not DefaultUpdateArgsId other) { return false; } return _workspaceKind == other._workspaceKind && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_workspaceKind.GetHashCode(), base.GetHashCode()); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Emitter/Model/SpecializedMethodReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a method of a generic type instantiation. /// e.g. /// A{int}.M() /// A.B{int}.C.M() /// </summary> internal class SpecializedMethodReference : MethodReference, Cci.ISpecializedMethodReference { public SpecializedMethodReference(MethodSymbol underlyingMethod) : base(underlyingMethod) { } public override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.ISpecializedMethodReference)this); } Cci.IMethodReference Cci.ISpecializedMethodReference.UnspecializedVersion { get { return UnderlyingMethod.OriginalDefinition.GetCciAdapter(); } } public override Cci.ISpecializedMethodReference AsSpecializedMethodReference { get { return this; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a method of a generic type instantiation. /// e.g. /// A{int}.M() /// A.B{int}.C.M() /// </summary> internal class SpecializedMethodReference : MethodReference, Cci.ISpecializedMethodReference { public SpecializedMethodReference(MethodSymbol underlyingMethod) : base(underlyingMethod) { } public override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.ISpecializedMethodReference)this); } Cci.IMethodReference Cci.ISpecializedMethodReference.UnspecializedVersion { get { return UnderlyingMethod.OriginalDefinition.GetCciAdapter(); } } public override Cci.ISpecializedMethodReference AsSpecializedMethodReference { get { return this; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Core/Portable/Symbols/Attributes/CommonFieldWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a field. /// </summary> internal class CommonFieldWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget { public CommonFieldWellKnownAttributeData() { _offset = Uninitialized; } #region FieldOffsetAttribute private int _offset; // may be Uninitialized private const int Uninitialized = -1; public void SetFieldOffset(int offset) { VerifySealed(expected: false); Debug.Assert(offset >= 0); _offset = offset; SetDataStored(); } public int? Offset { get { VerifySealed(expected: true); return _offset != Uninitialized ? _offset : (int?)null; } } #endregion #region DefaultParameterValue, DecimalConstant, DateTimeConstant private ConstantValue _constValue = ConstantValue.Unset; public ConstantValue ConstValue { get { return _constValue; } set { VerifySealed(expected: false); Debug.Assert(_constValue == ConstantValue.Unset); _constValue = value; SetDataStored(); } } #endregion #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region NonSerializedAttribute private bool _hasNonSerializedAttribute; public bool HasNonSerializedAttribute { get { VerifySealed(expected: true); return _hasNonSerializedAttribute; } set { VerifySealed(expected: false); _hasNonSerializedAttribute = value; SetDataStored(); } } #endregion #region MarshalAsAttribute private MarshalPseudoCustomAttributeData _lazyMarshalAsData; MarshalPseudoCustomAttributeData IMarshalAsAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazyMarshalAsData == null) { _lazyMarshalAsData = new MarshalPseudoCustomAttributeData(); SetDataStored(); } return _lazyMarshalAsData; } /// <summary> /// Returns marshalling data or null of MarshalAs attribute isn't applied on the field. /// </summary> public MarshalPseudoCustomAttributeData MarshallingInformation { get { VerifySealed(expected: true); return _lazyMarshalAsData; } } #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.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a field. /// </summary> internal class CommonFieldWellKnownAttributeData : WellKnownAttributeData, IMarshalAsAttributeTarget { public CommonFieldWellKnownAttributeData() { _offset = Uninitialized; } #region FieldOffsetAttribute private int _offset; // may be Uninitialized private const int Uninitialized = -1; public void SetFieldOffset(int offset) { VerifySealed(expected: false); Debug.Assert(offset >= 0); _offset = offset; SetDataStored(); } public int? Offset { get { VerifySealed(expected: true); return _offset != Uninitialized ? _offset : (int?)null; } } #endregion #region DefaultParameterValue, DecimalConstant, DateTimeConstant private ConstantValue _constValue = ConstantValue.Unset; public ConstantValue ConstValue { get { return _constValue; } set { VerifySealed(expected: false); Debug.Assert(_constValue == ConstantValue.Unset); _constValue = value; SetDataStored(); } } #endregion #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region NonSerializedAttribute private bool _hasNonSerializedAttribute; public bool HasNonSerializedAttribute { get { VerifySealed(expected: true); return _hasNonSerializedAttribute; } set { VerifySealed(expected: false); _hasNonSerializedAttribute = value; SetDataStored(); } } #endregion #region MarshalAsAttribute private MarshalPseudoCustomAttributeData _lazyMarshalAsData; MarshalPseudoCustomAttributeData IMarshalAsAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazyMarshalAsData == null) { _lazyMarshalAsData = new MarshalPseudoCustomAttributeData(); SetDataStored(); } return _lazyMarshalAsData; } /// <summary> /// Returns marshalling data or null of MarshalAs attribute isn't applied on the field. /// </summary> public MarshalPseudoCustomAttributeData MarshallingInformation { get { VerifySealed(expected: true); return _lazyMarshalAsData; } } #endregion } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/TodoComments/AbstractTodoCommentService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract class AbstractTodoCommentService : ITodoCommentService { protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia); protected abstract bool IsSingleLineComment(SyntaxTrivia trivia); protected abstract bool IsMultilineComment(SyntaxTrivia trivia); protected abstract bool IsIdentifierCharacter(char ch); protected abstract string GetNormalizedText(string message); protected abstract int GetCommentStartingIndex(string message); protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList); public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync( Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { if (commentDescriptors.IsEmpty) return ImmutableArray<TodoComment>.Empty; cancellationToken.ThrowIfCancellationRequested(); // strongly hold onto text and tree var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); // reuse list using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList); foreach (var trivia in syntaxDoc.Root.DescendantTrivia()) { cancellationToken.ThrowIfCancellationRequested(); if (!ContainsComments(trivia)) continue; AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList); } return todoList.ToImmutable(); } private bool ContainsComments(SyntaxTrivia trivia) => PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia); protected void AppendTodoCommentInfoFromSingleLine( ImmutableArray<TodoCommentDescriptor> commentDescriptors, string message, int start, ArrayBuilder<TodoComment> todoList) { var index = GetCommentStartingIndex(message); if (index >= message.Length) { return; } var normalized = GetNormalizedText(message); foreach (var commentDescriptor in commentDescriptors) { var token = commentDescriptor.Text; if (string.Compare( normalized, index, token, indexB: 0, length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0) { continue; } if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length])) { // they wrote something like: // todoboo // instead of // todo continue; } todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index)); } } protected void ProcessMultilineComment( ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, int postfixLength, ArrayBuilder<TodoComment> todoList) { // this is okay since we know it is already alive var text = document.Text; var fullSpan = trivia.FullSpan; var fullString = trivia.ToFullString(); var startLine = text.Lines.GetLineFromPosition(fullSpan.Start); var endLine = text.Lines.GetLineFromPosition(fullSpan.End); // single line multiline comments if (startLine.LineNumber == endLine.LineNumber) { var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList); return; } // multiline var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList); for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++) { var line = text.Lines[lineNumber]; var message = line.ToString(); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList); } var length = fullSpan.End - endLine.Start; if (length >= postfixLength) { length -= postfixLength; } var endMessage = text.ToString(new TextSpan(endLine.Start, length)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract class AbstractTodoCommentService : ITodoCommentService { protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia); protected abstract bool IsSingleLineComment(SyntaxTrivia trivia); protected abstract bool IsMultilineComment(SyntaxTrivia trivia); protected abstract bool IsIdentifierCharacter(char ch); protected abstract string GetNormalizedText(string message); protected abstract int GetCommentStartingIndex(string message); protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList); public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync( Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { if (commentDescriptors.IsEmpty) return ImmutableArray<TodoComment>.Empty; cancellationToken.ThrowIfCancellationRequested(); // strongly hold onto text and tree var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); // reuse list using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList); foreach (var trivia in syntaxDoc.Root.DescendantTrivia()) { cancellationToken.ThrowIfCancellationRequested(); if (!ContainsComments(trivia)) continue; AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList); } return todoList.ToImmutable(); } private bool ContainsComments(SyntaxTrivia trivia) => PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia); protected void AppendTodoCommentInfoFromSingleLine( ImmutableArray<TodoCommentDescriptor> commentDescriptors, string message, int start, ArrayBuilder<TodoComment> todoList) { var index = GetCommentStartingIndex(message); if (index >= message.Length) { return; } var normalized = GetNormalizedText(message); foreach (var commentDescriptor in commentDescriptors) { var token = commentDescriptor.Text; if (string.Compare( normalized, index, token, indexB: 0, length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0) { continue; } if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length])) { // they wrote something like: // todoboo // instead of // todo continue; } todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index)); } } protected void ProcessMultilineComment( ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, int postfixLength, ArrayBuilder<TodoComment> todoList) { // this is okay since we know it is already alive var text = document.Text; var fullSpan = trivia.FullSpan; var fullString = trivia.ToFullString(); var startLine = text.Lines.GetLineFromPosition(fullSpan.Start); var endLine = text.Lines.GetLineFromPosition(fullSpan.End); // single line multiline comments if (startLine.LineNumber == endLine.LineNumber) { var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList); return; } // multiline var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList); for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++) { var line = text.Lines[lineNumber]; var message = line.ToString(); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList); } var length = fullSpan.End - endLine.Start; if (length >= postfixLength) { length -= postfixLength; } var endMessage = text.ToString(new TextSpan(endLine.Start, length)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListenerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.TestHooks { /// <summary> /// Return <see cref="IAsynchronousOperationListener"/> for the given featureName /// /// We have this abstraction so that we can have isolated listener/waiter in unit tests /// </summary> internal interface IAsynchronousOperationListenerProvider { /// <summary> /// Get <see cref="IAsynchronousOperationListener"/> for given feature. /// same provider will return a singleton listener for same feature /// </summary> IAsynchronousOperationListener GetListener(string featureName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.TestHooks { /// <summary> /// Return <see cref="IAsynchronousOperationListener"/> for the given featureName /// /// We have this abstraction so that we can have isolated listener/waiter in unit tests /// </summary> internal interface IAsynchronousOperationListenerProvider { /// <summary> /// Get <see cref="IAsynchronousOperationListener"/> for given feature. /// same provider will return a singleton listener for same feature /// </summary> IAsynchronousOperationListener GetListener(string featureName); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Semantic/Semantics/GenericConstraintsTests.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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class GenericConstraintsTests : CompilingTestBase { [Fact] public void EnumConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (13,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(13, 26), // (14,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_Interface() { CreateCompilation(@" public class Test<T> where T : System.Enum, System.IDisposable { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.IDisposable { var a = new Test<E1>(); // not disposable var b = new Test<U>(); // not enum var c = new Test<int>(); // neither disposable nor enum } }").VerifyDiagnostics( // (13,26): error CS0315: The type 'E1' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'E1' to 'System.IDisposable'. // var a = new Test<E1>(); // not disposable Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E1").WithArguments("Test<T>", "System.IDisposable", "T", "E1").WithLocation(13, 26), // (14,26): error CS0314: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion or type parameter conversion from 'U' to 'System.Enum'. // var b = new Test<U>(); // not enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "U").WithArguments("Test<T>", "System.Enum", "T", "U").WithLocation(14, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(15, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.IDisposable'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.IDisposable", "T", "int").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Enum, new() { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26), // (15,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (11,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(11, 26), // (12,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ValueType() { var reference = CreateCompilation(@" public class Test<T> where T : struct, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum, new() { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26), // (13,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Enum { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'enum generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Enum").WithArguments("enum generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" enum E { } class Legacy { void M() { var a = new Test<E>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (10,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Enum'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Enum", "T", "Legacy").WithLocation(10, 26)); } [Theory] [InlineData("byte")] [InlineData("sbyte")] [InlineData("short")] [InlineData("ushort")] [InlineData("int")] [InlineData("uint")] [InlineData("long")] [InlineData("ulong")] public void EnumConstraint_DifferentBaseTypes(string type) { CreateCompilation($@" public class Test<T> where T : System.Enum {{ }} public enum E1 : {type} {{ A }} public class Test2 {{ public void M() {{ var a = new Test<E1>(); // Valid var b = new Test<int>(); // Invalid }} }} ").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26)); } [Fact] public void EnumConstraint_InheritanceChain() { CreateCompilation(@" public enum E { A } public class Test<T, U> where U : System.Enum, T { } public class Test2 { public void M() { var a = new Test<Test2, E>(); var b = new Test<E, E>(); var c = new Test<System.Enum, System.Enum>(); var d = new Test<E, System.Enum>(); var e = new Test<System.Enum, E>(); } }").VerifyDiagnostics( // (13,33): error CS0315: The type 'E' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no boxing conversion from 'E' to 'Test2'. // var a = new Test<Test2, E>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E").WithArguments("Test<T, U>", "Test2", "U", "E").WithLocation(13, 33), // (18,29): error CS0311: The type 'System.Enum' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Enum' to 'E'. // var d = new Test<E, System.Enum>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Enum").WithArguments("Test<T, U>", "E", "U", "System.Enum").WithLocation(18, 29)); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ValueType() { var code = "public class Test<T> where T : struct, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.True(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Enum, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }").VerifyDiagnostics( // (12,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(12, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }", references: new[] { reference }).VerifyDiagnostics( // (8,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(8, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Enum { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(8, 43)); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Enum { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(4, 43)); } [Fact] public void EnumConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public enum MyEnum { } public abstract class A<T> { public abstract void F<U>() where U : System.Enum, T; } public class B : A<MyEnum> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Enum", "MyEnum" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Enum { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Enum' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Enum").WithArguments("Enum", "System").WithLocation(7, 39)); } [Fact] public void EnumConstraint_BindingToMethods() { var code = @" enum A : short { a } enum B : uint { b } class Test { public static void Main() { Print(A.a); Print(B.b); } static void Print<T>(T obj) where T : System.Enum { System.Console.WriteLine(obj.GetTypeCode()); } }"; CompileAndVerify(code, expectedOutput: @" Int16 UInt32"); } [Fact] public void EnumConstraint_InheritingFromEnum() { var code = @" public class Child : System.Enum { } public enum E { A } public class Test { public void M<T>(T arg) where T : System.Enum { } public void N() { M(E.A); // valid M(new Child()); // invalid } }"; CreateCompilation(code).VerifyDiagnostics( // (2,22): error CS0644: 'Child' cannot derive from special class 'Enum' // public class Child : System.Enum Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.Enum").WithArguments("Child", "System.Enum").WithLocation(2, 22), // (20,9): error CS0311: The type 'Child' cannot be used as type parameter 'T' in the generic type or method 'Test.M<T>(T)'. There is no implicit reference conversion from 'Child' to 'System.Enum'. // M(new Child()); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Test.M<T>(T)", "System.Enum", "T", "Child").WithLocation(20, 9)); } [Fact] public void DelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Delegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(2, 40) ); } [Fact] public void DelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Delegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Delegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Delegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Delegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.Delegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.Delegate, System.Delegate>(); var d = new Test<System.MulticastDelegate, System.Delegate>(); var e = new Test<System.Delegate, System.MulticastDelegate>(); var f = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var g = new Test<D1, System.Delegate>(); var h = new Test<System.Delegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (14,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var d = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(14, 52), // (18,30): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'D1'. // var g = new Test<D1, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "D1", "U", "System.Delegate").WithLocation(18, 30)); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.Delegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Delegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Delegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(8, 43)); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Delegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(4, 43)); } [Fact] public void DelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.Delegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Delegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Delegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Delegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Delegate").WithArguments("Delegate", "System").WithLocation(7, 39)); } [Fact] public void DelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.Delegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void MulticastDelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.MulticastDelegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(2, 40) ); } [Fact] public void MulticastDelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.MulticastDelegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.MulticastDelegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.MulticastDelegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.MulticastDelegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.MulticastDelegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var d = new Test<System.Delegate, System.MulticastDelegate>(); var e = new Test<System.MulticastDelegate, System.Delegate>(); var f = new Test<System.Delegate, System.Delegate>(); var g = new Test<D1, System.MulticastDelegate>(); var h = new Test<System.MulticastDelegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (15,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var e = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(15, 52), // (16,43): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var f = new Test<System.Delegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(16, 43), // (18,30): error CS0311: The type 'System.MulticastDelegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.MulticastDelegate' to 'D1'. // var g = new Test<D1, System.MulticastDelegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.MulticastDelegate").WithArguments("Test<T, U>", "D1", "U", "System.MulticastDelegate").WithLocation(18, 30)); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.MulticastDelegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.MulticastDelegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(8, 43)); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(4, 43)); } [Fact] public void MulticastDelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.MulticastDelegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.MulticastDelegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.MulticastDelegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'MulticastDelegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MulticastDelegate").WithArguments("MulticastDelegate", "System").WithLocation(7, 39)); } [Fact] public void MulticastDelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.MulticastDelegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void ConversionInInheritanceChain_MulticastDelegate() { var code = @" class A<T> where T : System.Delegate { } class B<T> : A<T> where T : System.MulticastDelegate { }"; CreateCompilation(code).VerifyDiagnostics(); code = @" class A<T> where T : System.MulticastDelegate { } class B<T> : A<T> where T : System.Delegate { }"; CreateCompilation(code).VerifyDiagnostics( // (3,7): error CS0311: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. There is no implicit reference conversion from 'T' to 'System.MulticastDelegate'. // class B<T> : A<T> where T : System.Delegate { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("A<T>", "System.MulticastDelegate", "T", "T").WithLocation(3, 7)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Type() { CreateCompilation(@" public class Test<T> where T : unmanaged { } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (12,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(12, 26), // (13,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (16,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(16, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Method() { CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(13, 28), // (14,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(14, 28), // (17,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(17, 28) ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Delegate() { CreateCompilation(@" public delegate void D<T>() where T : unmanaged; public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }").VerifyDiagnostics( // (8,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(8, 32), // (9,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(9, 31), // (12,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(12, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_LocalFunction() { CreateCompilation(@" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { void M<T>() where T : unmanaged { } M<GoodType>(); // unmanaged struct M<BadType>(); // managed struct M<string>(); // reference type M<int>(); // value type M<U>(); // generic type constrained to unmanaged M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,9): error CS8377: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("M<T>()", "T", "BadType").WithLocation(13, 9), // (14,9): error CS8377: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("M<T>()", "T", "string").WithLocation(14, 9), // (17,9): error CS8377: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("M<T>()", "T", "W").WithLocation(17, 9)); } [Fact] public void UnmanagedConstraint_Compilation_ReferenceType() { var c = CreateCompilation("public class Test<T> where T : class, unmanaged {}"); c.VerifyDiagnostics( // (1,39): error CS0449: The 'unmanaged' constraint cannot be combined with the 'class' constraint // public class Test<T> where T : class, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 39)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_ValueType() { var c = CreateCompilation("public class Test<T> where T : struct, unmanaged {}"); c.VerifyDiagnostics( // (1,40): error CS0449: The 'unmanaged' constraint cannot be combined with the 'struct' constraint // public class Test<T> where T : struct, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 40)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_Constructor() { CreateCompilation("public class Test<T> where T : unmanaged, new() {}").VerifyDiagnostics( // (1,43): error CS8379: The 'new()' constraint cannot be used with the 'unmanaged' constraint // public class Test<T> where T : unmanaged, new() {} Diagnostic(ErrorCode.ERR_NewBoundWithUnmanaged, "new").WithLocation(1, 43)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_Before() { CreateCompilation("public class Test<T> where T : unmanaged, System.Exception { }").VerifyDiagnostics( // (1,43): error CS8380: 'Exception': cannot specify both a constraint class and the 'unmanaged' constraint // public class Test<T> where T : unmanaged, System.Exception { } Diagnostic(ErrorCode.ERR_UnmanagedBoundWithClass, "System.Exception").WithArguments("System.Exception").WithLocation(1, 43) ); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_After() { CreateCompilation("public class Test<T> where T : System.Exception, unmanaged { }").VerifyDiagnostics( // (1,50): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Exception, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 50)); } [Fact] public void UnmanagedConstraint_Compilation_OtherValidTypes_After() { CreateCompilation("public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { }").VerifyDiagnostics( // (1,65): error CS8376: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 65)); } [Fact] public void UnmanagedConstraint_OtherValidTypes_Before() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertEx.Equal(new string[] { "Enum", "IDisposable" }, typeParameter.ConstraintTypes().Select(type => type.Name)); }; CompileAndVerify( "public class Test<T> where T : unmanaged, System.Enum, System.IDisposable { }", sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_After() { CreateCompilation("public class Test<T, U> where T : U, unmanaged { }").VerifyDiagnostics( // (1,38): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T, U> where T : U, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 38)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_Before() { CreateCompilation("public class Test<T, U> where T : unmanaged, U { }").VerifyDiagnostics(); CreateCompilation("public class Test<T, U> where U: class where T : unmanaged, U, System.IDisposable { }").VerifyDiagnostics(); } [Fact] public void UnmanagedConstraint_UnmanagedEnumNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class ValueType {} } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (8,32): error CS0518: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType").WithLocation(8, 32)); } [Fact] public void UnmanagedConstraint_ValueTypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class Enum {} public class Int32 {} namespace Runtime { namespace InteropServices { public enum UnmanagedType {} } } } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (16,32): error CS0518: Predefined type 'System.ValueType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.ValueType").WithLocation(16, 32)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Type() { var reference = CreateCompilation(@" public class Test<T> where T : unmanaged { }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(9, 26), // (10,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(10, 26), // (13,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(13, 26)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Method() { var reference = CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(9, 28), // (10,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(10, 28), // (13,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(13, 28) ); } [Fact] public void UnmanagedConstraint_Reference_Alone_Delegate() { var reference = CreateCompilation(@" public delegate void D<T>() where T : unmanaged; ").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (7,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(7, 32), // (8,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(8, 31), // (11,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(11, 26)); } [Fact] public void UnmanagedConstraint_Before_7_3() { var code = @" public class Test<T> where T : unmanaged { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'unmanaged generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "unmanaged").WithArguments("unmanaged generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" class Legacy { void M() { var a = new Test<int>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS8377: The type 'Legacy' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Legacy").WithArguments("Test<T>", "T", "Legacy").WithLocation(7, 26)); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Type() { var code = "public class Test<T> where T : unmanaged { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } }"; CompileAndVerify(code, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" struct Test { public string RefMember { get; set; } } public abstract class A { public abstract void M<T>() where T : unmanaged; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }").VerifyDiagnostics( // (17,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(17, 14), // (18,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(18, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : unmanaged; }").EmitToImageReference(); CreateCompilation(@" struct Test { public string RefMember { get; set; } } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }", references: new[] { reference }).VerifyDiagnostics( // (13,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(13, 14), // (14,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(14, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : unmanaged { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(8, 43)); } [Fact] public void UnmanagedConstraint_StructMismatchInImplements() { CreateCompilation(@" public struct Segment<T> { public T[] array; } public interface I1<in T> where T : unmanaged { void Test<G>(G x) where G : unmanaged; } public class C2<T> : I1<T> where T : struct { public void Test<G>(G x) where G : struct { I1<T> i = this; i.Test(default(Segment<int>)); } } ").VerifyDiagnostics( // (11,14): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // public class C2<T> : I1<T> where T : struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "T").WithLocation(11, 14), // (13,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : struct Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(13, 17), // (15,12): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // I1<T> i = this; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "T").WithArguments("I1<T>", "T", "T").WithLocation(15, 12), // (16,11): error CS8377: The type 'Segment<int>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)' // i.Test(default(Segment<int>)); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Test").WithArguments("I1<T>.Test<G>(G)", "G", "Segment<int>").WithLocation(16, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplements() { CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } } ").VerifyDiagnostics( // (7,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(7, 14), // (9,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(9, 17), // (11,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(11, 12), // (13,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(13, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta() { var reference = CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } ").EmitToImageReference(); CreateCompilation(@" public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } }", references: new[] { reference }).VerifyDiagnostics( // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(2, 14), // (4,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(4, 17), // (6,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(6, 12), // (8,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(8, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta2() { var reference = CreateCompilation(@" public interface I1 { void Test<G>(ref G x) where G : unmanaged, System.IDisposable; } ").EmitToImageReference(); var reference1 = CreateCompilation(@" public class C1 : I1 { void I1.Test<G>(ref G x) { x.Dispose(); } }", references: new[] { reference }).EmitToImageReference(); ; CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } class Test { static void Main() { S local = default; I1 i = new C1(); i.Test(ref local); System.Console.WriteLine(local.a); } }", // NOTE: must pass verification (IDisposable constraint is copied over to the implementing method) options: TestOptions.UnsafeReleaseExe, references: new[] { reference, reference1 }, verify: Verification.Passes, expectedOutput: "123"); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : unmanaged { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(4, 43)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerOperations_Invalid() { CreateCompilation(@" class Test { void M<T>(T arg) where T : unmanaged { } void N() { M(""test""); } }").VerifyDiagnostics( // (9,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(9, 9)); } [ConditionalTheory(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [InlineData("(sbyte)1", "System.SByte", 1)] [InlineData("(byte)1", "System.Byte", 1)] [InlineData("(short)1", "System.Int16", 2)] [InlineData("(ushort)1", "System.UInt16", 2)] [InlineData("(int)1", "System.Int32", 4)] [InlineData("(uint)1", "System.UInt32", 4)] [InlineData("(long)1", "System.Int64", 8)] [InlineData("(ulong)1", "System.UInt64", 8)] [InlineData("'a'", "System.Char", 2)] [InlineData("(float)1", "System.Single", 4)] [InlineData("(double)1", "System.Double", 8)] [InlineData("(decimal)1", "System.Decimal", 16)] [InlineData("false", "System.Boolean", 1)] [InlineData("E.A", "E", 4)] [InlineData("new S { a = 1, b = 2, c = 3 }", "S", 12)] public void UnmanagedConstraints_PointerOperations_SimpleTypes(string arg, string type, int size) { CompileAndVerify(@" enum E { A } struct S { public int a; public int b; public int c; } unsafe class Test { static T* M<T>(T arg) where T : unmanaged { T* ptr = &arg; System.Console.WriteLine(ptr->GetType()); // method access System.Console.WriteLine(sizeof(T)); // sizeof operator T* ar = stackalloc T [10]; return ar; } static void Main() { M(" + arg + @"); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: string.Join(Environment.NewLine, type, size)).VerifyIL("Test.M<T>", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: conv.u IL_0003: constrained. ""T"" IL_0009: callvirt ""System.Type object.GetType()"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: sizeof ""T"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ldc.i4.s 10 IL_0020: conv.u IL_0021: sizeof ""T"" IL_0027: mul.ovf.un IL_0028: localloc IL_002a: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_InterfaceMethod() { CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } unsafe class Test { static void M<T>(ref T arg) where T : unmanaged, System.IDisposable { arg.Dispose(); fixed(T* ptr = &arg) { ptr->Dispose(); } } static void Main() { S local = default; M(ref local); System.Console.WriteLine(local.a); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "246").VerifyIL("Test.M<T>", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (pinned T& V_0) IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: callvirt ""void System.IDisposable.Dispose()"" IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: conv.u IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ldc.i4.0 IL_001c: conv.u IL_001d: stloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CtorAndValueTypeAreEmitted() { CompileAndVerify(@" using System.Linq; class Program { public static void M<T>() where T: unmanaged { } static void Main(string[] args) { var typeParam = typeof(Program).GetMethod(""M"").GetGenericArguments().First(); System.Console.WriteLine(typeParam.GenericParameterAttributes); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "NotNullableValueTypeConstraint, DefaultConstructorConstraint"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Flat() { CompileAndVerify(@" struct TestData { public int A; public TestData(int a) { A = a; } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "4"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Nested() { CompileAndVerify(@" struct InnerTestData { public int B; public InnerTestData(int b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, int b) { A = a; B = new InnerTestData(b); } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "8"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Error() { CreateCompilation(@" struct InnerTestData { public string B; public InnerTestData(string b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, string b) { A = a; B = new InnerTestData(b); } } class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { } }").VerifyDiagnostics( // (24,9): error CS8379: The type 'TestData' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.N<T>()' // N<TestData>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "N<TestData>").WithArguments("Test.N<T>()", "T", "TestData").WithLocation(24, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_InScope() { CompileAndVerify(@" class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } class Test { public static void Main() { M(new unmanaged()); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }", expectedOutput: "success"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_OutOfScope() { CreateCompilation(@" namespace hidden { class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } } class Test { public static void Main() { M(""test""); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }").VerifyDiagnostics( // (16,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(16, 9), // (20,13): error CS1061: 'T' does not contain a definition for 'Print' and no extension method 'Print' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.Print(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Print").WithArguments("T", "Print").WithLocation(20, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Methods() { CompileAndVerify(@" class Program { static void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } static void B<T>(T arg) where T : unmanaged { A(arg); } static void Main() { B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Types() { CompileAndVerify(@" class A<T> where T : struct { public void M(T arg) { System.Console.WriteLine(arg); } } class B<T> : A<T> where T : unmanaged { } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Interfaces() { CompileAndVerify(@" interface A<T> where T : struct { void M(T arg); } class B<T> : A<T> where T : unmanaged { public void M(T arg) { System.Console.WriteLine(arg); } } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_LocalFunctions() { CompileAndVerify(@" class Program { static void Main() { void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } void B<T>(T arg) where T : unmanaged { A(arg); } B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerTypeSubstitution() { var compilation = CreateCompilation(@" unsafe public class Test { public T* M<T>() where T : unmanaged => throw null; public void N() { var result = M<int>(); } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var value = ((VariableDeclaratorSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.VariableDeclarator)).Initializer.Value; Assert.Equal("M<int>()", value.ToFullString()); var symbol = (IMethodSymbol)model.GetSymbolInfo(value).Symbol; Assert.Equal("System.Int32*", symbol.ReturnType.ToTestDisplayString()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CannotConstraintToTypeParameterConstrainedByUnmanaged() { CreateCompilation(@" class Test<U> where U : unmanaged { void M<T>() where T : U { } }").VerifyDiagnostics( // (4,12): error CS8379: Type parameter 'U' has the 'unmanaged' constraint so 'U' cannot be used as a constraint for 'T' // void M<T>() where T : U Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "T").WithArguments("T", "U").WithLocation(4, 12)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedAsTypeConstraintName() { CreateCompilation(@" class Test<unmanaged> where unmanaged : System.IDisposable { void M<T>(T arg) where T : unmanaged { arg.Dispose(); arg.NonExistentMethod(); } }").VerifyDiagnostics( // (7,13): error CS1061: 'T' does not contain a definition for 'NonExistentMethod' and no extension method 'NonExistentMethod' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.NonExistentMethod(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "NonExistentMethod").WithArguments("T", "NonExistentMethod").WithLocation(7, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CircularReferenceToUnmanagedTypeWillBindSuccessfully() { CreateCompilation(@" public unsafe class C<U> where U : unmanaged { public void M1<T>() where T : T* { } public void M2<T>() where T : U* { } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M2<T>() where T : U* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(5, 35), // (4,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M1<T>() where T : T* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "T*").WithLocation(4, 35)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_EnumWithUnmanaged() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal("Enum", typeParameter.ConstraintTypes().Single().Name); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); }; CompileAndVerify( source: "public class Test<T> where T : unmanaged, System.Enum {}", sourceSymbolValidator: validator, symbolValidator: validator); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedInGenericType() { var code = @" public class Wrapper<T> { public enum E { } public struct S { } } public class Test { void IsUnmanaged<T>() where T : unmanaged { } void IsEnum<T>() where T : System.Enum { } void IsStruct<T>() where T : struct { } void IsNew<T>() where T : new() { } void User() { IsUnmanaged<Wrapper<int>.E>(); IsEnum<Wrapper<int>.E>(); IsStruct<Wrapper<int>.E>(); IsNew<Wrapper<int>.E>(); IsUnmanaged<Wrapper<int>.S>(); IsEnum<Wrapper<int>.S>(); // Invalid IsStruct<Wrapper<int>.S>(); IsNew<Wrapper<int>.S>(); IsUnmanaged<Wrapper<string>.E>(); IsEnum<Wrapper<string>.E>(); IsStruct<Wrapper<string>.E>(); IsNew<Wrapper<string>.E>(); IsUnmanaged<Wrapper<string>.S>(); IsEnum<Wrapper<string>.S>(); // Invalid IsStruct<Wrapper<string>.S>(); IsNew<Wrapper<string>.S>(); } }"; CreateCompilation(code).VerifyDiagnostics( // (28,9): error CS0315: The type 'Wrapper<int>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<int>.S' to 'System.Enum'. // IsEnum<Wrapper<int>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<int>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<int>.S").WithLocation(28, 9), // (38,9): error CS0315: The type 'Wrapper<string>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<string>.S' to 'System.Enum'. // IsEnum<Wrapper<string>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<string>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<string>.S").WithLocation(38, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerInsideStruct() { CompileAndVerify(@" unsafe struct S { public int a; public int* b; public S(int a, int* b) { this.a = a; this.b = b; } } unsafe class Test { static T* M<T>() where T : unmanaged { System.Console.WriteLine(typeof(T).FullName); T* ar = null; return ar; } static void Main() { S* ar = M<S>(); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "S"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_LambdaTypeParameters() { CompileAndVerify(@" public delegate T D<T>() where T : unmanaged; public class Test<U1> where U1 : unmanaged { public static void Print<T>(D<T> lambda) where T : unmanaged { System.Console.WriteLine(lambda()); } public static void User1(U1 arg) { Print(() => arg); } public static void User2<U2>(U2 arg) where U2 : unmanaged { Print(() => arg); } } public class Program { public static void Main() { // Testing the constraint when the lambda type parameter is both coming from an enclosing type, or copied to the generated lambda class Test<int>.User1(1); Test<int>.User2(2); } }", expectedOutput: @" 1 2", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.True(module.ContainingAssembly.GetTypeByMetadataName("D`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").GetTypeMember("<>c__DisplayClass2_0").TypeParameters.Single().HasUnmanagedTypeConstraint); }); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_IsConsideredDuringOverloadResolution() { CompileAndVerify(@" public class Program { static void Test<T>(T arg) where T : unmanaged { System.Console.WriteLine(""Unmanaged: "" + arg); } static void Test(object arg) { System.Console.WriteLine(""Object: "" + arg); } static void User<U>(U arg) where U : unmanaged { Test(1); // should pick up the first, as it is better than the second one (which requires a conversion) Test(""2""); // should pick up the second, as it is the only candidate Test(arg); // should pick up the first, as it is the only candidate } static void Main() { User(3); } }", expectedOutput: @" Unmanaged: 1 Object: 2 Unmanaged: 3"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { var p = stackalloc T[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_CallFromADifferentMethod() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { } unsafe void N() { var p = stackalloc int[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { M(null, b); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs_CallFromADifferentMethod() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { } static void N() { M(null, 5); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_Errors() { CreateCompilation(@" unsafe class C { void Unmanaged<T>(T* a) where T : unmanaged { } void UnmanagedWithInterface<T>(T* a) where T : unmanaged, System.IDisposable { } void Test() { int a = 0; Unmanaged(0); // fail (type inference) Unmanaged(a); // fail (type inference) Unmanaged(&a); // succeed (unmanaged type pointer) UnmanagedWithInterface(0); // fail (type inference) UnmanagedWithInterface(a); // fail (type inference) UnmanagedWithInterface(&a); // fail (does not match interface) } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (14,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(14, 9), // (15,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(15, 9), // (18,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(19, 9), // (20,9): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'C.UnmanagedWithInterface<T>(T*)'. There is no boxing conversion from 'int' to 'System.IDisposable'. // UnmanagedWithInterface(&a); // fail (does not match interface) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)", "System.IDisposable", "T", "int").WithLocation(20, 9)); } [Fact] public void UnmanagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void ManagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2<T>(MyStruct<T>* ms) where T : unmanaged { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12)); } [Fact] public void UnmanagedGenericConstraintStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct OuterStruct { public int x; public InnerStruct inner; } public struct InnerStruct { public int y; } public class C { public unsafe void M() { MyStruct<OuterStruct> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<OuterStruct>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedGenericStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18), // (17,12): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M2(&myStruct); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&myStruct").WithArguments("unmanaged constructed types", "8.0").WithLocation(17, 12), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55)); } [Fact] public void UnmanagedGenericStructMultipleConstraints() { // A diagnostic will only be produced for the first violated constraint. var code = @" public struct MyStruct<T> where T : unmanaged, System.IDisposable { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct = default; _ = myStruct; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (16,18): error CS0315: The type 'InnerStruct<int>' cannot be used as type parameter 'T' in the generic type or method 'MyStruct<T>'. There is no boxing conversion from 'InnerStruct<int>' to 'System.IDisposable'. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "InnerStruct<int>").WithArguments("MyStruct<T>", "System.IDisposable", "T", "InnerStruct<int>").WithLocation(16, 18) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18) ); } [Fact] public void UnmanagedGenericConstraintPartialConstructedStruct() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M<U>() { MyStruct<U> myStruct; M2<U>(&myStruct); } public unsafe void M2<V>(MyStruct<V>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (11,18): error CS8377: The type 'U' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // MyStruct<U> myStruct; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "U").WithArguments("MyStruct<T>", "T", "U").WithLocation(11, 18), // (12,15): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<U>') // M2<U>(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<U>").WithLocation(12, 15), // (15,43): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<V>') // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<V>").WithLocation(15, 43), // (15,43): error CS8377: The type 'V' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "ms").WithArguments("MyStruct<T>", "T", "V").WithLocation(15, 43)); } [Fact] public void GenericStructManagedFieldPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<string>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12), // (15,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // public unsafe void M2(MyStruct<string>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<string>").WithLocation(15, 45)); } [Fact] public void UnmanagedRecursiveGenericStruct() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public YourStruct<T>* field; } public unsafe struct YourStruct<T> where T : unmanaged { public MyStruct<T>* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveStruct() { var code = @" public unsafe struct MyStruct { public YourStruct* field; } public unsafe struct YourStruct { public MyStruct* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgument() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedCyclic() { var code = @" public struct MyStruct<T> { public YourStruct<T> field; } public struct YourStruct<T> where T : unmanaged { public MyStruct<T> field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,26): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<T>' causes a cycle in the struct layout // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<T>").WithLocation(4, 26), // (4,26): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "T").WithLocation(4, 26), // (9,24): error CS0523: Struct member 'YourStruct<T>.field' of type 'MyStruct<T>' causes a cycle in the struct layout // public MyStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("YourStruct<T>.field", "MyStruct<T>").WithLocation(9, 24)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentManagedGenericField() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public T myField; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentConstraintViolation() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public string s; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveTypeArgumentConstraintViolation_02() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; public string s; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.True(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void NestedGenericStructContainingPointer() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T* field; public T this[int index] { get { return field[index]; } } } public class C { public static unsafe void Main() { float f = 42; var ms = new MyStruct<float> { field = &f }; var test = new MyStruct<MyStruct<float>> { field = &ms }; float value = test[0][0]; System.Console.Write(value); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, expectedOutput: "42", verify: Verification.Skipped); } [Fact] public void SimpleGenericStructPointer_ILValidation() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T field; public static void Test() { var ms = new MyStruct<int>(); MyStruct<int>* ptr = &ms; ptr->field = 42; } } "; var il = @" { // Code size 19 (0x13) .maxstack 2 .locals init (MyStruct<int> V_0) //ms IL_0000: ldloca.s V_0 IL_0002: initobj ""MyStruct<int>"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: ldc.i4.s 42 IL_000d: stfld ""int MyStruct<int>.field"" IL_0012: ret } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseDll, verify: Verification.Skipped) .VerifyIL("MyStruct<T>.Test", il); } [Fact, WorkItem(31439, "https://github.com/dotnet/roslyn/issues/31439")] public void CircularTypeArgumentUnmanagedConstraint() { var code = @" public struct X<T> where T : unmanaged { } public struct Z { public X<Z> field; }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("Z").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void GenericStructAddressOfRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var ms = new MyStruct<int>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var ptr = &ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 19) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructFixedRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Test(MyClass c) { fixed (MyStruct<int>* ptr = &c.ms) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,16): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>*").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 16), // (12,37): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&c.ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 37)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructSizeofRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var size = sizeof(MyStruct<int>); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,20): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var size = sizeof(MyStruct<int>); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "sizeof(MyStruct<int>)").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 20) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericImplicitStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc[] { new MyStruct<int>() }; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc[] { new MyStruct<int>() }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc[] { new MyStruct<int>() }").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 19)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc MyStruct<int>[4]; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,30): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc MyStruct<int>[4]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 30)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public unsafe struct OtherStruct { public MyStruct<int>* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,27): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 27) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericNestedStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public struct InnerStruct { public T field; } } public unsafe struct OtherStruct { public MyStruct<int>.InnerStruct* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,39): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>.InnerStruct* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 39) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingTuple_Unmanaged_RequiresCSharp8() { var code = @" public struct MyStruct { public (int, int) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2() { M<MyStruct>(); M<(int, int)>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (14,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<(int, int)>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<(int, int)>").WithArguments("unmanaged constructed types", "8.0").WithLocation(14, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingGenericTuple_Unmanaged() { var code = @" public struct MyStruct<T> { public (T, T) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2<U>() where U : unmanaged { M<MyStruct<U>>(); } public void M3<V>() { M<MyStruct<V>>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct<U>>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct<U>>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); } [Fact] public void GenericRefStructAddressOf_01() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>() { field = 42 }; var ptr = &ms; System.Console.Write(ptr->field); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericRefStructAddressOf_02() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public unsafe void M() { var ms = new MyStruct<object>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<object>') // var ptr = &ms; Diagnostic(ErrorCode.ERR_ManagedAddr, "&ms").WithArguments("MyStruct<object>").WithLocation(12, 19) ); } [Fact] public void GenericStructFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Main() { var c = new MyClass(); c.ms.field = 42; fixed (MyStruct<int>* ptr = &c.ms) { System.Console.Write(ptr->field); } } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericStructLocalFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>(); fixed (int* ptr = &ms.field) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,27): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* ptr = &ms.field) Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&ms.field").WithLocation(12, 27) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics() { var comp = CreateCompilation(@" class C1<T1> where T1 : class, struct, unmanaged, notnull { void M1<T2>() where T2 : class, struct, unmanaged, notnull {} } class C2<T1> where T1 : struct, class, unmanaged, notnull { void M2<T2>() where T2 : struct, class, unmanaged, notnull {} } class C3<T1> where T1 : class, class { void M3<T2>() where T2 : class, class {} } "); comp.VerifyDiagnostics( // (2,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(2, 32), // (2,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(2, 40), // (2,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(2, 51), // (4,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(4, 37), // (4,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(4, 45), // (4,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 56), // (6,33): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(6, 33), // (6,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(6, 40), // (6,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(6, 51), // (8,38): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 38), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(8, 45), // (8,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(8, 56), // (10,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C3<T1> where T1 : class, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(10, 32), // (12,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M3<T2>() where T2 : class, class {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(12, 37) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics_InheritedClassStruct() { var comp = CreateCompilation(@" class C { public virtual void M<T1>() where T1 : class {} } class D : C { public override void M<T1>() where T1 : C, class, struct {} } class E { public virtual void M<T2>() where T2 : struct {} } class F : E { public override void M<T2>() where T2 : E, struct, class {} } class G { public virtual void M<T3>() where T3 : unmanaged {} } class H : G { public override void M<T3>() where T3 : G, unmanaged, struct {} } "); comp.VerifyDiagnostics( // (8,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T1>() where T1 : C, class, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "C").WithLocation(8, 45), // (16,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T2>() where T2 : E, struct, class {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "E").WithLocation(16, 45), // (24,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T3>() where T3 : G, unmanaged, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "G").WithLocation(24, 45) ); } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class GenericConstraintsTests : CompilingTestBase { [Fact] public void EnumConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (13,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(13, 26), // (14,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_Interface() { CreateCompilation(@" public class Test<T> where T : System.Enum, System.IDisposable { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.IDisposable { var a = new Test<E1>(); // not disposable var b = new Test<U>(); // not enum var c = new Test<int>(); // neither disposable nor enum } }").VerifyDiagnostics( // (13,26): error CS0315: The type 'E1' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'E1' to 'System.IDisposable'. // var a = new Test<E1>(); // not disposable Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E1").WithArguments("Test<T>", "System.IDisposable", "T", "E1").WithLocation(13, 26), // (14,26): error CS0314: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion or type parameter conversion from 'U' to 'System.Enum'. // var b = new Test<U>(); // not enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "U").WithArguments("Test<T>", "System.Enum", "T", "U").WithLocation(14, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(15, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.IDisposable'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.IDisposable", "T", "int").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Enum, new() { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26), // (15,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (11,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(11, 26), // (12,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ValueType() { var reference = CreateCompilation(@" public class Test<T> where T : struct, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum, new() { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26), // (13,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Enum { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'enum generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Enum").WithArguments("enum generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" enum E { } class Legacy { void M() { var a = new Test<E>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (10,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Enum'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Enum", "T", "Legacy").WithLocation(10, 26)); } [Theory] [InlineData("byte")] [InlineData("sbyte")] [InlineData("short")] [InlineData("ushort")] [InlineData("int")] [InlineData("uint")] [InlineData("long")] [InlineData("ulong")] public void EnumConstraint_DifferentBaseTypes(string type) { CreateCompilation($@" public class Test<T> where T : System.Enum {{ }} public enum E1 : {type} {{ A }} public class Test2 {{ public void M() {{ var a = new Test<E1>(); // Valid var b = new Test<int>(); // Invalid }} }} ").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26)); } [Fact] public void EnumConstraint_InheritanceChain() { CreateCompilation(@" public enum E { A } public class Test<T, U> where U : System.Enum, T { } public class Test2 { public void M() { var a = new Test<Test2, E>(); var b = new Test<E, E>(); var c = new Test<System.Enum, System.Enum>(); var d = new Test<E, System.Enum>(); var e = new Test<System.Enum, E>(); } }").VerifyDiagnostics( // (13,33): error CS0315: The type 'E' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no boxing conversion from 'E' to 'Test2'. // var a = new Test<Test2, E>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E").WithArguments("Test<T, U>", "Test2", "U", "E").WithLocation(13, 33), // (18,29): error CS0311: The type 'System.Enum' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Enum' to 'E'. // var d = new Test<E, System.Enum>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Enum").WithArguments("Test<T, U>", "E", "U", "System.Enum").WithLocation(18, 29)); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ValueType() { var code = "public class Test<T> where T : struct, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.True(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Enum, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }").VerifyDiagnostics( // (12,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(12, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }", references: new[] { reference }).VerifyDiagnostics( // (8,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(8, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Enum { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(8, 43)); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Enum { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(4, 43)); } [Fact] public void EnumConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public enum MyEnum { } public abstract class A<T> { public abstract void F<U>() where U : System.Enum, T; } public class B : A<MyEnum> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Enum", "MyEnum" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Enum { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Enum' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Enum").WithArguments("Enum", "System").WithLocation(7, 39)); } [Fact] public void EnumConstraint_BindingToMethods() { var code = @" enum A : short { a } enum B : uint { b } class Test { public static void Main() { Print(A.a); Print(B.b); } static void Print<T>(T obj) where T : System.Enum { System.Console.WriteLine(obj.GetTypeCode()); } }"; CompileAndVerify(code, expectedOutput: @" Int16 UInt32"); } [Fact] public void EnumConstraint_InheritingFromEnum() { var code = @" public class Child : System.Enum { } public enum E { A } public class Test { public void M<T>(T arg) where T : System.Enum { } public void N() { M(E.A); // valid M(new Child()); // invalid } }"; CreateCompilation(code).VerifyDiagnostics( // (2,22): error CS0644: 'Child' cannot derive from special class 'Enum' // public class Child : System.Enum Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.Enum").WithArguments("Child", "System.Enum").WithLocation(2, 22), // (20,9): error CS0311: The type 'Child' cannot be used as type parameter 'T' in the generic type or method 'Test.M<T>(T)'. There is no implicit reference conversion from 'Child' to 'System.Enum'. // M(new Child()); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Test.M<T>(T)", "System.Enum", "T", "Child").WithLocation(20, 9)); } [Fact] public void DelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Delegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(2, 40) ); } [Fact] public void DelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Delegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Delegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Delegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Delegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.Delegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.Delegate, System.Delegate>(); var d = new Test<System.MulticastDelegate, System.Delegate>(); var e = new Test<System.Delegate, System.MulticastDelegate>(); var f = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var g = new Test<D1, System.Delegate>(); var h = new Test<System.Delegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (14,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var d = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(14, 52), // (18,30): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'D1'. // var g = new Test<D1, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "D1", "U", "System.Delegate").WithLocation(18, 30)); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.Delegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Delegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Delegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(8, 43)); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Delegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(4, 43)); } [Fact] public void DelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.Delegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Delegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Delegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Delegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Delegate").WithArguments("Delegate", "System").WithLocation(7, 39)); } [Fact] public void DelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.Delegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void MulticastDelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.MulticastDelegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(2, 40) ); } [Fact] public void MulticastDelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.MulticastDelegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.MulticastDelegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.MulticastDelegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.MulticastDelegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.MulticastDelegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var d = new Test<System.Delegate, System.MulticastDelegate>(); var e = new Test<System.MulticastDelegate, System.Delegate>(); var f = new Test<System.Delegate, System.Delegate>(); var g = new Test<D1, System.MulticastDelegate>(); var h = new Test<System.MulticastDelegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (15,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var e = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(15, 52), // (16,43): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var f = new Test<System.Delegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(16, 43), // (18,30): error CS0311: The type 'System.MulticastDelegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.MulticastDelegate' to 'D1'. // var g = new Test<D1, System.MulticastDelegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.MulticastDelegate").WithArguments("Test<T, U>", "D1", "U", "System.MulticastDelegate").WithLocation(18, 30)); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.MulticastDelegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.MulticastDelegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(8, 43)); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(4, 43)); } [Fact] public void MulticastDelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.MulticastDelegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.MulticastDelegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.MulticastDelegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'MulticastDelegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MulticastDelegate").WithArguments("MulticastDelegate", "System").WithLocation(7, 39)); } [Fact] public void MulticastDelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.MulticastDelegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void ConversionInInheritanceChain_MulticastDelegate() { var code = @" class A<T> where T : System.Delegate { } class B<T> : A<T> where T : System.MulticastDelegate { }"; CreateCompilation(code).VerifyDiagnostics(); code = @" class A<T> where T : System.MulticastDelegate { } class B<T> : A<T> where T : System.Delegate { }"; CreateCompilation(code).VerifyDiagnostics( // (3,7): error CS0311: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. There is no implicit reference conversion from 'T' to 'System.MulticastDelegate'. // class B<T> : A<T> where T : System.Delegate { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("A<T>", "System.MulticastDelegate", "T", "T").WithLocation(3, 7)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Type() { CreateCompilation(@" public class Test<T> where T : unmanaged { } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (12,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(12, 26), // (13,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (16,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(16, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Method() { CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(13, 28), // (14,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(14, 28), // (17,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(17, 28) ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Delegate() { CreateCompilation(@" public delegate void D<T>() where T : unmanaged; public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }").VerifyDiagnostics( // (8,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(8, 32), // (9,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(9, 31), // (12,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(12, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_LocalFunction() { CreateCompilation(@" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { void M<T>() where T : unmanaged { } M<GoodType>(); // unmanaged struct M<BadType>(); // managed struct M<string>(); // reference type M<int>(); // value type M<U>(); // generic type constrained to unmanaged M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,9): error CS8377: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("M<T>()", "T", "BadType").WithLocation(13, 9), // (14,9): error CS8377: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("M<T>()", "T", "string").WithLocation(14, 9), // (17,9): error CS8377: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("M<T>()", "T", "W").WithLocation(17, 9)); } [Fact] public void UnmanagedConstraint_Compilation_ReferenceType() { var c = CreateCompilation("public class Test<T> where T : class, unmanaged {}"); c.VerifyDiagnostics( // (1,39): error CS0449: The 'unmanaged' constraint cannot be combined with the 'class' constraint // public class Test<T> where T : class, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 39)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_ValueType() { var c = CreateCompilation("public class Test<T> where T : struct, unmanaged {}"); c.VerifyDiagnostics( // (1,40): error CS0449: The 'unmanaged' constraint cannot be combined with the 'struct' constraint // public class Test<T> where T : struct, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 40)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_Constructor() { CreateCompilation("public class Test<T> where T : unmanaged, new() {}").VerifyDiagnostics( // (1,43): error CS8379: The 'new()' constraint cannot be used with the 'unmanaged' constraint // public class Test<T> where T : unmanaged, new() {} Diagnostic(ErrorCode.ERR_NewBoundWithUnmanaged, "new").WithLocation(1, 43)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_Before() { CreateCompilation("public class Test<T> where T : unmanaged, System.Exception { }").VerifyDiagnostics( // (1,43): error CS8380: 'Exception': cannot specify both a constraint class and the 'unmanaged' constraint // public class Test<T> where T : unmanaged, System.Exception { } Diagnostic(ErrorCode.ERR_UnmanagedBoundWithClass, "System.Exception").WithArguments("System.Exception").WithLocation(1, 43) ); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_After() { CreateCompilation("public class Test<T> where T : System.Exception, unmanaged { }").VerifyDiagnostics( // (1,50): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Exception, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 50)); } [Fact] public void UnmanagedConstraint_Compilation_OtherValidTypes_After() { CreateCompilation("public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { }").VerifyDiagnostics( // (1,65): error CS8376: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 65)); } [Fact] public void UnmanagedConstraint_OtherValidTypes_Before() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertEx.Equal(new string[] { "Enum", "IDisposable" }, typeParameter.ConstraintTypes().Select(type => type.Name)); }; CompileAndVerify( "public class Test<T> where T : unmanaged, System.Enum, System.IDisposable { }", sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_After() { CreateCompilation("public class Test<T, U> where T : U, unmanaged { }").VerifyDiagnostics( // (1,38): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T, U> where T : U, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 38)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_Before() { CreateCompilation("public class Test<T, U> where T : unmanaged, U { }").VerifyDiagnostics(); CreateCompilation("public class Test<T, U> where U: class where T : unmanaged, U, System.IDisposable { }").VerifyDiagnostics(); } [Fact] public void UnmanagedConstraint_UnmanagedEnumNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class ValueType {} } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (8,32): error CS0518: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType").WithLocation(8, 32)); } [Fact] public void UnmanagedConstraint_ValueTypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class Enum {} public class Int32 {} namespace Runtime { namespace InteropServices { public enum UnmanagedType {} } } } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (16,32): error CS0518: Predefined type 'System.ValueType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.ValueType").WithLocation(16, 32)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Type() { var reference = CreateCompilation(@" public class Test<T> where T : unmanaged { }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(9, 26), // (10,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(10, 26), // (13,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(13, 26)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Method() { var reference = CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(9, 28), // (10,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(10, 28), // (13,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(13, 28) ); } [Fact] public void UnmanagedConstraint_Reference_Alone_Delegate() { var reference = CreateCompilation(@" public delegate void D<T>() where T : unmanaged; ").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (7,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(7, 32), // (8,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(8, 31), // (11,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(11, 26)); } [Fact] public void UnmanagedConstraint_Before_7_3() { var code = @" public class Test<T> where T : unmanaged { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'unmanaged generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "unmanaged").WithArguments("unmanaged generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" class Legacy { void M() { var a = new Test<int>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS8377: The type 'Legacy' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Legacy").WithArguments("Test<T>", "T", "Legacy").WithLocation(7, 26)); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Type() { var code = "public class Test<T> where T : unmanaged { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } }"; CompileAndVerify(code, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" struct Test { public string RefMember { get; set; } } public abstract class A { public abstract void M<T>() where T : unmanaged; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }").VerifyDiagnostics( // (17,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(17, 14), // (18,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(18, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : unmanaged; }").EmitToImageReference(); CreateCompilation(@" struct Test { public string RefMember { get; set; } } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }", references: new[] { reference }).VerifyDiagnostics( // (13,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(13, 14), // (14,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(14, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : unmanaged { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(8, 43)); } [Fact] public void UnmanagedConstraint_StructMismatchInImplements() { CreateCompilation(@" public struct Segment<T> { public T[] array; } public interface I1<in T> where T : unmanaged { void Test<G>(G x) where G : unmanaged; } public class C2<T> : I1<T> where T : struct { public void Test<G>(G x) where G : struct { I1<T> i = this; i.Test(default(Segment<int>)); } } ").VerifyDiagnostics( // (11,14): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // public class C2<T> : I1<T> where T : struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "T").WithLocation(11, 14), // (13,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : struct Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(13, 17), // (15,12): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // I1<T> i = this; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "T").WithArguments("I1<T>", "T", "T").WithLocation(15, 12), // (16,11): error CS8377: The type 'Segment<int>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)' // i.Test(default(Segment<int>)); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Test").WithArguments("I1<T>.Test<G>(G)", "G", "Segment<int>").WithLocation(16, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplements() { CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } } ").VerifyDiagnostics( // (7,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(7, 14), // (9,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(9, 17), // (11,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(11, 12), // (13,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(13, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta() { var reference = CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } ").EmitToImageReference(); CreateCompilation(@" public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } }", references: new[] { reference }).VerifyDiagnostics( // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(2, 14), // (4,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(4, 17), // (6,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(6, 12), // (8,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(8, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta2() { var reference = CreateCompilation(@" public interface I1 { void Test<G>(ref G x) where G : unmanaged, System.IDisposable; } ").EmitToImageReference(); var reference1 = CreateCompilation(@" public class C1 : I1 { void I1.Test<G>(ref G x) { x.Dispose(); } }", references: new[] { reference }).EmitToImageReference(); ; CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } class Test { static void Main() { S local = default; I1 i = new C1(); i.Test(ref local); System.Console.WriteLine(local.a); } }", // NOTE: must pass verification (IDisposable constraint is copied over to the implementing method) options: TestOptions.UnsafeReleaseExe, references: new[] { reference, reference1 }, verify: Verification.Passes, expectedOutput: "123"); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : unmanaged { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(4, 43)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerOperations_Invalid() { CreateCompilation(@" class Test { void M<T>(T arg) where T : unmanaged { } void N() { M(""test""); } }").VerifyDiagnostics( // (9,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(9, 9)); } [ConditionalTheory(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [InlineData("(sbyte)1", "System.SByte", 1)] [InlineData("(byte)1", "System.Byte", 1)] [InlineData("(short)1", "System.Int16", 2)] [InlineData("(ushort)1", "System.UInt16", 2)] [InlineData("(int)1", "System.Int32", 4)] [InlineData("(uint)1", "System.UInt32", 4)] [InlineData("(long)1", "System.Int64", 8)] [InlineData("(ulong)1", "System.UInt64", 8)] [InlineData("'a'", "System.Char", 2)] [InlineData("(float)1", "System.Single", 4)] [InlineData("(double)1", "System.Double", 8)] [InlineData("(decimal)1", "System.Decimal", 16)] [InlineData("false", "System.Boolean", 1)] [InlineData("E.A", "E", 4)] [InlineData("new S { a = 1, b = 2, c = 3 }", "S", 12)] public void UnmanagedConstraints_PointerOperations_SimpleTypes(string arg, string type, int size) { CompileAndVerify(@" enum E { A } struct S { public int a; public int b; public int c; } unsafe class Test { static T* M<T>(T arg) where T : unmanaged { T* ptr = &arg; System.Console.WriteLine(ptr->GetType()); // method access System.Console.WriteLine(sizeof(T)); // sizeof operator T* ar = stackalloc T [10]; return ar; } static void Main() { M(" + arg + @"); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: string.Join(Environment.NewLine, type, size)).VerifyIL("Test.M<T>", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: conv.u IL_0003: constrained. ""T"" IL_0009: callvirt ""System.Type object.GetType()"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: sizeof ""T"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ldc.i4.s 10 IL_0020: conv.u IL_0021: sizeof ""T"" IL_0027: mul.ovf.un IL_0028: localloc IL_002a: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_InterfaceMethod() { CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } unsafe class Test { static void M<T>(ref T arg) where T : unmanaged, System.IDisposable { arg.Dispose(); fixed(T* ptr = &arg) { ptr->Dispose(); } } static void Main() { S local = default; M(ref local); System.Console.WriteLine(local.a); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "246").VerifyIL("Test.M<T>", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (pinned T& V_0) IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: callvirt ""void System.IDisposable.Dispose()"" IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: conv.u IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ldc.i4.0 IL_001c: conv.u IL_001d: stloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CtorAndValueTypeAreEmitted() { CompileAndVerify(@" using System.Linq; class Program { public static void M<T>() where T: unmanaged { } static void Main(string[] args) { var typeParam = typeof(Program).GetMethod(""M"").GetGenericArguments().First(); System.Console.WriteLine(typeParam.GenericParameterAttributes); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "NotNullableValueTypeConstraint, DefaultConstructorConstraint"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Flat() { CompileAndVerify(@" struct TestData { public int A; public TestData(int a) { A = a; } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "4"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Nested() { CompileAndVerify(@" struct InnerTestData { public int B; public InnerTestData(int b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, int b) { A = a; B = new InnerTestData(b); } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "8"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Error() { CreateCompilation(@" struct InnerTestData { public string B; public InnerTestData(string b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, string b) { A = a; B = new InnerTestData(b); } } class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { } }").VerifyDiagnostics( // (24,9): error CS8379: The type 'TestData' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.N<T>()' // N<TestData>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "N<TestData>").WithArguments("Test.N<T>()", "T", "TestData").WithLocation(24, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_InScope() { CompileAndVerify(@" class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } class Test { public static void Main() { M(new unmanaged()); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }", expectedOutput: "success"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_OutOfScope() { CreateCompilation(@" namespace hidden { class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } } class Test { public static void Main() { M(""test""); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }").VerifyDiagnostics( // (16,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(16, 9), // (20,13): error CS1061: 'T' does not contain a definition for 'Print' and no extension method 'Print' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.Print(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Print").WithArguments("T", "Print").WithLocation(20, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Methods() { CompileAndVerify(@" class Program { static void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } static void B<T>(T arg) where T : unmanaged { A(arg); } static void Main() { B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Types() { CompileAndVerify(@" class A<T> where T : struct { public void M(T arg) { System.Console.WriteLine(arg); } } class B<T> : A<T> where T : unmanaged { } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Interfaces() { CompileAndVerify(@" interface A<T> where T : struct { void M(T arg); } class B<T> : A<T> where T : unmanaged { public void M(T arg) { System.Console.WriteLine(arg); } } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_LocalFunctions() { CompileAndVerify(@" class Program { static void Main() { void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } void B<T>(T arg) where T : unmanaged { A(arg); } B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerTypeSubstitution() { var compilation = CreateCompilation(@" unsafe public class Test { public T* M<T>() where T : unmanaged => throw null; public void N() { var result = M<int>(); } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var value = ((VariableDeclaratorSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.VariableDeclarator)).Initializer.Value; Assert.Equal("M<int>()", value.ToFullString()); var symbol = (IMethodSymbol)model.GetSymbolInfo(value).Symbol; Assert.Equal("System.Int32*", symbol.ReturnType.ToTestDisplayString()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CannotConstraintToTypeParameterConstrainedByUnmanaged() { CreateCompilation(@" class Test<U> where U : unmanaged { void M<T>() where T : U { } }").VerifyDiagnostics( // (4,12): error CS8379: Type parameter 'U' has the 'unmanaged' constraint so 'U' cannot be used as a constraint for 'T' // void M<T>() where T : U Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "T").WithArguments("T", "U").WithLocation(4, 12)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedAsTypeConstraintName() { CreateCompilation(@" class Test<unmanaged> where unmanaged : System.IDisposable { void M<T>(T arg) where T : unmanaged { arg.Dispose(); arg.NonExistentMethod(); } }").VerifyDiagnostics( // (7,13): error CS1061: 'T' does not contain a definition for 'NonExistentMethod' and no extension method 'NonExistentMethod' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.NonExistentMethod(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "NonExistentMethod").WithArguments("T", "NonExistentMethod").WithLocation(7, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CircularReferenceToUnmanagedTypeWillBindSuccessfully() { CreateCompilation(@" public unsafe class C<U> where U : unmanaged { public void M1<T>() where T : T* { } public void M2<T>() where T : U* { } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M2<T>() where T : U* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(5, 35), // (4,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M1<T>() where T : T* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "T*").WithLocation(4, 35)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_EnumWithUnmanaged() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal("Enum", typeParameter.ConstraintTypes().Single().Name); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); }; CompileAndVerify( source: "public class Test<T> where T : unmanaged, System.Enum {}", sourceSymbolValidator: validator, symbolValidator: validator); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedInGenericType() { var code = @" public class Wrapper<T> { public enum E { } public struct S { } } public class Test { void IsUnmanaged<T>() where T : unmanaged { } void IsEnum<T>() where T : System.Enum { } void IsStruct<T>() where T : struct { } void IsNew<T>() where T : new() { } void User() { IsUnmanaged<Wrapper<int>.E>(); IsEnum<Wrapper<int>.E>(); IsStruct<Wrapper<int>.E>(); IsNew<Wrapper<int>.E>(); IsUnmanaged<Wrapper<int>.S>(); IsEnum<Wrapper<int>.S>(); // Invalid IsStruct<Wrapper<int>.S>(); IsNew<Wrapper<int>.S>(); IsUnmanaged<Wrapper<string>.E>(); IsEnum<Wrapper<string>.E>(); IsStruct<Wrapper<string>.E>(); IsNew<Wrapper<string>.E>(); IsUnmanaged<Wrapper<string>.S>(); IsEnum<Wrapper<string>.S>(); // Invalid IsStruct<Wrapper<string>.S>(); IsNew<Wrapper<string>.S>(); } }"; CreateCompilation(code).VerifyDiagnostics( // (28,9): error CS0315: The type 'Wrapper<int>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<int>.S' to 'System.Enum'. // IsEnum<Wrapper<int>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<int>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<int>.S").WithLocation(28, 9), // (38,9): error CS0315: The type 'Wrapper<string>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<string>.S' to 'System.Enum'. // IsEnum<Wrapper<string>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<string>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<string>.S").WithLocation(38, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerInsideStruct() { CompileAndVerify(@" unsafe struct S { public int a; public int* b; public S(int a, int* b) { this.a = a; this.b = b; } } unsafe class Test { static T* M<T>() where T : unmanaged { System.Console.WriteLine(typeof(T).FullName); T* ar = null; return ar; } static void Main() { S* ar = M<S>(); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "S"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_LambdaTypeParameters() { CompileAndVerify(@" public delegate T D<T>() where T : unmanaged; public class Test<U1> where U1 : unmanaged { public static void Print<T>(D<T> lambda) where T : unmanaged { System.Console.WriteLine(lambda()); } public static void User1(U1 arg) { Print(() => arg); } public static void User2<U2>(U2 arg) where U2 : unmanaged { Print(() => arg); } } public class Program { public static void Main() { // Testing the constraint when the lambda type parameter is both coming from an enclosing type, or copied to the generated lambda class Test<int>.User1(1); Test<int>.User2(2); } }", expectedOutput: @" 1 2", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.True(module.ContainingAssembly.GetTypeByMetadataName("D`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").GetTypeMember("<>c__DisplayClass2_0").TypeParameters.Single().HasUnmanagedTypeConstraint); }); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_IsConsideredDuringOverloadResolution() { CompileAndVerify(@" public class Program { static void Test<T>(T arg) where T : unmanaged { System.Console.WriteLine(""Unmanaged: "" + arg); } static void Test(object arg) { System.Console.WriteLine(""Object: "" + arg); } static void User<U>(U arg) where U : unmanaged { Test(1); // should pick up the first, as it is better than the second one (which requires a conversion) Test(""2""); // should pick up the second, as it is the only candidate Test(arg); // should pick up the first, as it is the only candidate } static void Main() { User(3); } }", expectedOutput: @" Unmanaged: 1 Object: 2 Unmanaged: 3"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { var p = stackalloc T[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_CallFromADifferentMethod() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { } unsafe void N() { var p = stackalloc int[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { M(null, b); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs_CallFromADifferentMethod() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { } static void N() { M(null, 5); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_Errors() { CreateCompilation(@" unsafe class C { void Unmanaged<T>(T* a) where T : unmanaged { } void UnmanagedWithInterface<T>(T* a) where T : unmanaged, System.IDisposable { } void Test() { int a = 0; Unmanaged(0); // fail (type inference) Unmanaged(a); // fail (type inference) Unmanaged(&a); // succeed (unmanaged type pointer) UnmanagedWithInterface(0); // fail (type inference) UnmanagedWithInterface(a); // fail (type inference) UnmanagedWithInterface(&a); // fail (does not match interface) } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (14,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(14, 9), // (15,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(15, 9), // (18,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(19, 9), // (20,9): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'C.UnmanagedWithInterface<T>(T*)'. There is no boxing conversion from 'int' to 'System.IDisposable'. // UnmanagedWithInterface(&a); // fail (does not match interface) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)", "System.IDisposable", "T", "int").WithLocation(20, 9)); } [Fact] public void UnmanagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void ManagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2<T>(MyStruct<T>* ms) where T : unmanaged { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12)); } [Fact] public void UnmanagedGenericConstraintStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct OuterStruct { public int x; public InnerStruct inner; } public struct InnerStruct { public int y; } public class C { public unsafe void M() { MyStruct<OuterStruct> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<OuterStruct>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedGenericStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18), // (17,12): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M2(&myStruct); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&myStruct").WithArguments("unmanaged constructed types", "8.0").WithLocation(17, 12), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55)); } [Fact] public void UnmanagedGenericStructMultipleConstraints() { // A diagnostic will only be produced for the first violated constraint. var code = @" public struct MyStruct<T> where T : unmanaged, System.IDisposable { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct = default; _ = myStruct; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (16,18): error CS0315: The type 'InnerStruct<int>' cannot be used as type parameter 'T' in the generic type or method 'MyStruct<T>'. There is no boxing conversion from 'InnerStruct<int>' to 'System.IDisposable'. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "InnerStruct<int>").WithArguments("MyStruct<T>", "System.IDisposable", "T", "InnerStruct<int>").WithLocation(16, 18) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18) ); } [Fact] public void UnmanagedGenericConstraintPartialConstructedStruct() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M<U>() { MyStruct<U> myStruct; M2<U>(&myStruct); } public unsafe void M2<V>(MyStruct<V>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (11,18): error CS8377: The type 'U' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // MyStruct<U> myStruct; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "U").WithArguments("MyStruct<T>", "T", "U").WithLocation(11, 18), // (12,15): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<U>') // M2<U>(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<U>").WithLocation(12, 15), // (15,43): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<V>') // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<V>").WithLocation(15, 43), // (15,43): error CS8377: The type 'V' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "ms").WithArguments("MyStruct<T>", "T", "V").WithLocation(15, 43)); } [Fact] public void GenericStructManagedFieldPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<string>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12), // (15,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // public unsafe void M2(MyStruct<string>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<string>").WithLocation(15, 45)); } [Fact] public void UnmanagedRecursiveGenericStruct() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public YourStruct<T>* field; } public unsafe struct YourStruct<T> where T : unmanaged { public MyStruct<T>* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveStruct() { var code = @" public unsafe struct MyStruct { public YourStruct* field; } public unsafe struct YourStruct { public MyStruct* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgument() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedCyclic() { var code = @" public struct MyStruct<T> { public YourStruct<T> field; } public struct YourStruct<T> where T : unmanaged { public MyStruct<T> field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,26): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<T>' causes a cycle in the struct layout // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<T>").WithLocation(4, 26), // (4,26): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "T").WithLocation(4, 26), // (9,24): error CS0523: Struct member 'YourStruct<T>.field' of type 'MyStruct<T>' causes a cycle in the struct layout // public MyStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("YourStruct<T>.field", "MyStruct<T>").WithLocation(9, 24)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentManagedGenericField() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public T myField; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentConstraintViolation() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public string s; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveTypeArgumentConstraintViolation_02() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; public string s; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.True(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void NestedGenericStructContainingPointer() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T* field; public T this[int index] { get { return field[index]; } } } public class C { public static unsafe void Main() { float f = 42; var ms = new MyStruct<float> { field = &f }; var test = new MyStruct<MyStruct<float>> { field = &ms }; float value = test[0][0]; System.Console.Write(value); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, expectedOutput: "42", verify: Verification.Skipped); } [Fact] public void SimpleGenericStructPointer_ILValidation() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T field; public static void Test() { var ms = new MyStruct<int>(); MyStruct<int>* ptr = &ms; ptr->field = 42; } } "; var il = @" { // Code size 19 (0x13) .maxstack 2 .locals init (MyStruct<int> V_0) //ms IL_0000: ldloca.s V_0 IL_0002: initobj ""MyStruct<int>"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: ldc.i4.s 42 IL_000d: stfld ""int MyStruct<int>.field"" IL_0012: ret } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseDll, verify: Verification.Skipped) .VerifyIL("MyStruct<T>.Test", il); } [Fact, WorkItem(31439, "https://github.com/dotnet/roslyn/issues/31439")] public void CircularTypeArgumentUnmanagedConstraint() { var code = @" public struct X<T> where T : unmanaged { } public struct Z { public X<Z> field; }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("Z").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void GenericStructAddressOfRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var ms = new MyStruct<int>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var ptr = &ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 19) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructFixedRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Test(MyClass c) { fixed (MyStruct<int>* ptr = &c.ms) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,16): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>*").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 16), // (12,37): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&c.ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 37)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructSizeofRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var size = sizeof(MyStruct<int>); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,20): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var size = sizeof(MyStruct<int>); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "sizeof(MyStruct<int>)").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 20) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericImplicitStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc[] { new MyStruct<int>() }; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc[] { new MyStruct<int>() }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc[] { new MyStruct<int>() }").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 19)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc MyStruct<int>[4]; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,30): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc MyStruct<int>[4]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 30)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public unsafe struct OtherStruct { public MyStruct<int>* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,27): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 27) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericNestedStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public struct InnerStruct { public T field; } } public unsafe struct OtherStruct { public MyStruct<int>.InnerStruct* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,39): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>.InnerStruct* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 39) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingTuple_Unmanaged_RequiresCSharp8() { var code = @" public struct MyStruct { public (int, int) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2() { M<MyStruct>(); M<(int, int)>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (14,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<(int, int)>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<(int, int)>").WithArguments("unmanaged constructed types", "8.0").WithLocation(14, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingGenericTuple_Unmanaged() { var code = @" public struct MyStruct<T> { public (T, T) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2<U>() where U : unmanaged { M<MyStruct<U>>(); } public void M3<V>() { M<MyStruct<V>>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct<U>>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct<U>>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); } [Fact] public void GenericRefStructAddressOf_01() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>() { field = 42 }; var ptr = &ms; System.Console.Write(ptr->field); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericRefStructAddressOf_02() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public unsafe void M() { var ms = new MyStruct<object>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<object>') // var ptr = &ms; Diagnostic(ErrorCode.ERR_ManagedAddr, "&ms").WithArguments("MyStruct<object>").WithLocation(12, 19) ); } [Fact] public void GenericStructFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Main() { var c = new MyClass(); c.ms.field = 42; fixed (MyStruct<int>* ptr = &c.ms) { System.Console.Write(ptr->field); } } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericStructLocalFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>(); fixed (int* ptr = &ms.field) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,27): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* ptr = &ms.field) Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&ms.field").WithLocation(12, 27) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics() { var comp = CreateCompilation(@" class C1<T1> where T1 : class, struct, unmanaged, notnull { void M1<T2>() where T2 : class, struct, unmanaged, notnull {} } class C2<T1> where T1 : struct, class, unmanaged, notnull { void M2<T2>() where T2 : struct, class, unmanaged, notnull {} } class C3<T1> where T1 : class, class { void M3<T2>() where T2 : class, class {} } "); comp.VerifyDiagnostics( // (2,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(2, 32), // (2,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(2, 40), // (2,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(2, 51), // (4,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(4, 37), // (4,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(4, 45), // (4,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 56), // (6,33): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(6, 33), // (6,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(6, 40), // (6,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(6, 51), // (8,38): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 38), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(8, 45), // (8,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(8, 56), // (10,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C3<T1> where T1 : class, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(10, 32), // (12,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M3<T2>() where T2 : class, class {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(12, 37) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics_InheritedClassStruct() { var comp = CreateCompilation(@" class C { public virtual void M<T1>() where T1 : class {} } class D : C { public override void M<T1>() where T1 : C, class, struct {} } class E { public virtual void M<T2>() where T2 : struct {} } class F : E { public override void M<T2>() where T2 : E, struct, class {} } class G { public virtual void M<T3>() where T3 : unmanaged {} } class H : G { public override void M<T3>() where T3 : G, unmanaged, struct {} } "); comp.VerifyDiagnostics( // (8,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T1>() where T1 : C, class, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "C").WithLocation(8, 45), // (16,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T2>() where T2 : E, struct, class {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "E").WithLocation(16, 45), // (24,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T3>() where T3 : G, unmanaged, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "G").WithLocation(24, 45) ); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/SolutionCrawler/HostSolutionCrawlerWorkspaceEventListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: true); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodAsynchronous { public partial class MakeMethodAsynchronousTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeMethodAsynchronousTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeMethodAsynchronousCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] public async Task AwaitInTaskMainMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task Main() { await Task.Delay(1); } }"; await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)); // no option offered to keep void await TestActionCountAsync(initial, count: 1, new TestParameters(compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() { var initial = @"using System; using System.Threading.Tasks; class Program { public void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public async void Main() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInVoidMethodWithModifiers2() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodNoModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/Task/*Comment*/Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/async Task/*Comment*/Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaFunction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = () => [|await Task.Run(a);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = async () => await Task.Run(a); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaAction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = async () => await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod() { var initial = @"using System.Threading.Tasks; class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod2() { var initial = @"using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod3() { var initial = @"using System.Threading.Tasks; class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod4() { var initial = @"using System.Threading.Tasks; class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod5() { var initial = @"class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod6() { var initial = @"class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod7() { var initial = @"class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod8() { var initial = @"class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod9() { var initial = @"class Program { Program Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<Program> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod10() { var initial = @"class Program { asdf Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<asdf> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return local(); IEnumerable<int> local() { yield return 1; } } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return local(); IEnumerable<int> local() { yield return 1; } } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerator<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInMember() { var code = @"using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate3() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task NullNodeCrash() { await TestMissingInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { static async void Main() { try { [|await|] await Task.Delay(100); } finally { } } }"); } [WorkItem(17470, "https://github.com/dotnet/roslyn/issues/17470")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInValueTaskMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { ValueTask<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { async ValueTask<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInValueTaskWithoutGenericMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { ValueTask Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { async ValueTask Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task AddAsyncInLocalFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async Task M2Async() { await M3Async(); } } async Task<int> M3Async() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepVoidReturn() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async void M2() { await M3Async(); } } async Task<int> M3Async() { return 1; } }", index: 1); } [Theory] [InlineData(0, "void", "Task", "M2Async")] [InlineData(1, "void", "void", "M2")] [InlineData(0, "int", "Task<int>", "M2Async")] [InlineData(0, "Task", "Task", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {initialReturn} /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Theory] [InlineData("", 0, "Task", "M2Async")] [InlineData("", 1, "void", "M2")] [InlineData("public", 0, "Task", "M2Async")] [InlineData("public", 1, "void", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitUsing() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await using (var x = new object())|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await using (var x = new object()) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularUsing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using (var x = new object())|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEach() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var n in new int[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEach() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var n in new int[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var (a, b) in new(int, int)[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var (a, b) in new(int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEachVariable() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var (a, b) in new(int, int)[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithNullableReturn() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { string? M() { [|await Task.Delay(1);|] return null; } }", @"#nullable enable using System.Threading.Tasks; class C { async Task<string?> MAsync() { await Task.Delay(1); return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumerableMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumeratorMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodAsynchronous { public partial class MakeMethodAsynchronousTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeMethodAsynchronousTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeMethodAsynchronousCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] public async Task AwaitInTaskMainMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task Main() { await Task.Delay(1); } }"; await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)); // no option offered to keep void await TestActionCountAsync(initial, count: 1, new TestParameters(compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() { var initial = @"using System; using System.Threading.Tasks; class Program { public void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public async void Main() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInVoidMethodWithModifiers2() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodNoModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/Task/*Comment*/Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/async Task/*Comment*/Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaFunction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = () => [|await Task.Run(a);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = async () => await Task.Run(a); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaAction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = async () => await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod() { var initial = @"using System.Threading.Tasks; class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod2() { var initial = @"using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod3() { var initial = @"using System.Threading.Tasks; class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod4() { var initial = @"using System.Threading.Tasks; class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod5() { var initial = @"class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod6() { var initial = @"class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod7() { var initial = @"class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod8() { var initial = @"class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod9() { var initial = @"class Program { Program Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<Program> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod10() { var initial = @"class Program { asdf Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<asdf> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return local(); IEnumerable<int> local() { yield return 1; } } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return local(); IEnumerable<int> local() { yield return 1; } } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerator<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInMember() { var code = @"using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate3() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task NullNodeCrash() { await TestMissingInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { static async void Main() { try { [|await|] await Task.Delay(100); } finally { } } }"); } [WorkItem(17470, "https://github.com/dotnet/roslyn/issues/17470")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInValueTaskMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { ValueTask<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { async ValueTask<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInValueTaskWithoutGenericMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { ValueTask Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { async ValueTask Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task AddAsyncInLocalFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async Task M2Async() { await M3Async(); } } async Task<int> M3Async() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepVoidReturn() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async void M2() { await M3Async(); } } async Task<int> M3Async() { return 1; } }", index: 1); } [Theory] [InlineData(0, "void", "Task", "M2Async")] [InlineData(1, "void", "void", "M2")] [InlineData(0, "int", "Task<int>", "M2Async")] [InlineData(0, "Task", "Task", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {initialReturn} /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Theory] [InlineData("", 0, "Task", "M2Async")] [InlineData("", 1, "void", "M2")] [InlineData("public", 0, "Task", "M2Async")] [InlineData("public", 1, "void", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitUsing() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await using (var x = new object())|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await using (var x = new object()) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularUsing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using (var x = new object())|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEach() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var n in new int[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEach() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var n in new int[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var (a, b) in new(int, int)[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var (a, b) in new(int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEachVariable() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var (a, b) in new(int, int)[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithNullableReturn() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { string? M() { [|await Task.Delay(1);|] return null; } }", @"#nullable enable using System.Threading.Tasks; class C { async Task<string?> MAsync() { await Task.Delay(1); return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumerableMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumeratorMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/ImplementType/ImplementTypeOptionsProvider.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ImplementType { [ExportOptionProvider, Shared] internal class ImplementTypeOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ImplementTypeOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ImplementTypeOptions.InsertionBehavior); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ImplementType { [ExportOptionProvider, Shared] internal class ImplementTypeOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ImplementTypeOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ImplementTypeOptions.InsertionBehavior); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/FlowAnalysis/CSharpDataFlowAnalysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This class implements the region data flow analysis operations. Region data flow analysis /// provides information how data flows into and out of a region. The analysis is done lazily. /// When created, it performs no analysis, but simply caches the arguments. Then, the first time /// one of the analysis results is used it computes that one result and caches it. Each result /// is computed using a custom algorithm. /// </summary> internal class CSharpDataFlowAnalysis : DataFlowAnalysis { private readonly RegionAnalysisContext _context; private ImmutableArray<ISymbol> _variablesDeclared; private HashSet<Symbol> _unassignedVariables; private ImmutableArray<ISymbol> _dataFlowsIn; private ImmutableArray<ISymbol> _dataFlowsOut; private ImmutableArray<ISymbol> _definitelyAssignedOnEntry; private ImmutableArray<ISymbol> _definitelyAssignedOnExit; private ImmutableArray<ISymbol> _alwaysAssigned; private ImmutableArray<ISymbol> _readInside; private ImmutableArray<ISymbol> _writtenInside; private ImmutableArray<ISymbol> _readOutside; private ImmutableArray<ISymbol> _writtenOutside; private ImmutableArray<ISymbol> _captured; private ImmutableArray<IMethodSymbol> _usedLocalFunctions; private ImmutableArray<ISymbol> _capturedInside; private ImmutableArray<ISymbol> _capturedOutside; private ImmutableArray<ISymbol> _unsafeAddressTaken; private HashSet<PrefixUnaryExpressionSyntax> _unassignedVariableAddressOfSyntaxes; private bool? _succeeded; internal CSharpDataFlowAnalysis(RegionAnalysisContext context) { _context = context; } /// <summary> /// A collection of the local variables that are declared within the region. Note that the region must be /// bounded by a method's body or a field's initializer, so method parameter symbols are never included /// in the result, but lambda parameters might appear in the result. /// </summary> public override ImmutableArray<ISymbol> VariablesDeclared { // Variables declared in the region is computed by a simple scan. // ISSUE: are these only variables declared at the top level in the region, // or are we to include variables declared in deeper scopes within the region? get { if (_variablesDeclared.IsDefault) { var result = Succeeded ? Normalize(VariablesDeclaredWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _variablesDeclared, result); } return _variablesDeclared; } } private HashSet<Symbol> UnassignedVariables { get { if (_unassignedVariables == null) { var result = Succeeded ? UnassignedVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet<Symbol>(); Interlocked.CompareExchange(ref _unassignedVariables, result, null); } return _unassignedVariables; } } /// <summary> /// A collection of the local variables for which a value assigned outside the region may be used inside the region. /// </summary> public override ImmutableArray<ISymbol> DataFlowsIn { get { if (_dataFlowsIn.IsDefault) { _succeeded = !_context.Failed; var result = _context.Failed ? ImmutableArray<ISymbol>.Empty : Normalize(DataFlowsInWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, UnassignedVariableAddressOfSyntaxes, out _succeeded)); ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsIn, result); } return _dataFlowsIn; } } /// <summary> /// The set of local variables which are definitely assigned a value when a region is /// entered. /// </summary> public override ImmutableArray<ISymbol> DefinitelyAssignedOnEntry => ComputeDefinitelyAssignedValues().onEntry; /// <summary> /// The set of local variables which are definitely assigned a value when a region is /// exited. /// </summary> public override ImmutableArray<ISymbol> DefinitelyAssignedOnExit => ComputeDefinitelyAssignedValues().onExit; private (ImmutableArray<ISymbol> onEntry, ImmutableArray<ISymbol> onExit) ComputeDefinitelyAssignedValues() { // Check for _definitelyAssignedOnExit as that's the last thing we write to. If it's not // Default, then we'll have written to both variables and can safely read from either of // them. if (_definitelyAssignedOnExit.IsDefault) { var entryResult = ImmutableArray<ISymbol>.Empty; var exitResult = ImmutableArray<ISymbol>.Empty; if (Succeeded) { var (entry, exit) = DefinitelyAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion); entryResult = Normalize(entry); exitResult = Normalize(exit); } ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnEntry, entryResult); ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnExit, exitResult); } return (_definitelyAssignedOnEntry, _definitelyAssignedOnExit); } /// <summary> /// A collection of the local variables for which a value assigned inside the region may be used outside the region. /// Note that every reachable assignment to a ref or out variable will be included in the results. /// </summary> public override ImmutableArray<ISymbol> DataFlowsOut { get { var discarded = DataFlowsIn; // force DataFlowsIn to be computed if (_dataFlowsOut.IsDefault) { var result = Succeeded ? Normalize(DataFlowsOutWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, _dataFlowsIn)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsOut, result); } return _dataFlowsOut; } } /// <summary> /// A collection of the local variables for which a value is always assigned inside the region. /// </summary> public override ImmutableArray<ISymbol> AlwaysAssigned { get { if (_alwaysAssigned.IsDefault) { var result = Succeeded ? Normalize(AlwaysAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _alwaysAssigned, result); } return _alwaysAssigned; } } /// <summary> /// A collection of the local variables that are read inside the region. /// </summary> public override ImmutableArray<ISymbol> ReadInside { get { if (_readInside.IsDefault) { AnalyzeReadWrite(); } return _readInside; } } /// <summary> /// A collection of local variables that are written inside the region. /// </summary> public override ImmutableArray<ISymbol> WrittenInside { get { if (_writtenInside.IsDefault) { AnalyzeReadWrite(); } return _writtenInside; } } /// <summary> /// A collection of the local variables that are read outside the region. /// </summary> public override ImmutableArray<ISymbol> ReadOutside { get { if (_readOutside.IsDefault) { AnalyzeReadWrite(); } return _readOutside; } } /// <summary> /// A collection of local variables that are written outside the region. /// </summary> public override ImmutableArray<ISymbol> WrittenOutside { get { if (_writtenOutside.IsDefault) { AnalyzeReadWrite(); } return _writtenOutside; } } private void AnalyzeReadWrite() { IEnumerable<Symbol> readInside, writtenInside, readOutside, writtenOutside, captured, unsafeAddressTaken, capturedInside, capturedOutside; IEnumerable<MethodSymbol> usedLocalFunctions; if (Succeeded) { ReadWriteWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariableAddressOfSyntaxes, readInside: out readInside, writtenInside: out writtenInside, readOutside: out readOutside, writtenOutside: out writtenOutside, captured: out captured, unsafeAddressTaken: out unsafeAddressTaken, capturedInside: out capturedInside, capturedOutside: out capturedOutside, usedLocalFunctions: out usedLocalFunctions); } else { readInside = writtenInside = readOutside = writtenOutside = captured = unsafeAddressTaken = capturedInside = capturedOutside = Enumerable.Empty<Symbol>(); usedLocalFunctions = Enumerable.Empty<MethodSymbol>(); } ImmutableInterlocked.InterlockedInitialize(ref _readInside, Normalize(readInside)); ImmutableInterlocked.InterlockedInitialize(ref _writtenInside, Normalize(writtenInside)); ImmutableInterlocked.InterlockedInitialize(ref _readOutside, Normalize(readOutside)); ImmutableInterlocked.InterlockedInitialize(ref _writtenOutside, Normalize(writtenOutside)); ImmutableInterlocked.InterlockedInitialize(ref _captured, Normalize(captured)); ImmutableInterlocked.InterlockedInitialize(ref _capturedInside, Normalize(capturedInside)); ImmutableInterlocked.InterlockedInitialize(ref _capturedOutside, Normalize(capturedOutside)); ImmutableInterlocked.InterlockedInitialize(ref _unsafeAddressTaken, Normalize(unsafeAddressTaken)); ImmutableInterlocked.InterlockedInitialize(ref _usedLocalFunctions, Normalize(usedLocalFunctions)); } /// <summary> /// A collection of the non-constant local variables and parameters that have been referenced in anonymous functions /// and therefore must be moved to a field of a frame class. /// </summary> public override ImmutableArray<ISymbol> Captured { get { if (_captured.IsDefault) { AnalyzeReadWrite(); } return _captured; } } public override ImmutableArray<ISymbol> CapturedInside { get { if (_capturedInside.IsDefault) { AnalyzeReadWrite(); } return _capturedInside; } } public override ImmutableArray<ISymbol> CapturedOutside { get { if (_capturedOutside.IsDefault) { AnalyzeReadWrite(); } return _capturedOutside; } } /// <summary> /// A collection of the non-constant local variables and parameters that have had their address (or the address of one /// of their fields) taken using the '&amp;' operator. /// </summary> /// <remarks> /// If there are any of these in the region, then a method should not be extracted. /// </remarks> public override ImmutableArray<ISymbol> UnsafeAddressTaken { get { if (_unsafeAddressTaken.IsDefault) { AnalyzeReadWrite(); } return _unsafeAddressTaken; } } public override ImmutableArray<IMethodSymbol> UsedLocalFunctions { get { if (_usedLocalFunctions.IsDefault) { AnalyzeReadWrite(); } return _usedLocalFunctions; } } private HashSet<PrefixUnaryExpressionSyntax> UnassignedVariableAddressOfSyntaxes { get { if (_unassignedVariableAddressOfSyntaxes == null) { var result = Succeeded ? UnassignedAddressTakenVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet<PrefixUnaryExpressionSyntax>(); Interlocked.CompareExchange(ref _unassignedVariableAddressOfSyntaxes, result, null); } return _unassignedVariableAddressOfSyntaxes; } } /// <summary> /// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression, /// a single statement, or a contiguous series of statements within the enclosing block. /// </summary> public sealed override bool Succeeded { get { if (_succeeded == null) { var discarded = DataFlowsIn; } return _succeeded.Value; } } private static ImmutableArray<ISymbol> Normalize(IEnumerable<Symbol> data) { return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).GetPublicSymbols()); } private static ImmutableArray<IMethodSymbol> Normalize(IEnumerable<MethodSymbol> data) { return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).Select(p => p.GetPublicSymbol())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This class implements the region data flow analysis operations. Region data flow analysis /// provides information how data flows into and out of a region. The analysis is done lazily. /// When created, it performs no analysis, but simply caches the arguments. Then, the first time /// one of the analysis results is used it computes that one result and caches it. Each result /// is computed using a custom algorithm. /// </summary> internal class CSharpDataFlowAnalysis : DataFlowAnalysis { private readonly RegionAnalysisContext _context; private ImmutableArray<ISymbol> _variablesDeclared; private HashSet<Symbol> _unassignedVariables; private ImmutableArray<ISymbol> _dataFlowsIn; private ImmutableArray<ISymbol> _dataFlowsOut; private ImmutableArray<ISymbol> _definitelyAssignedOnEntry; private ImmutableArray<ISymbol> _definitelyAssignedOnExit; private ImmutableArray<ISymbol> _alwaysAssigned; private ImmutableArray<ISymbol> _readInside; private ImmutableArray<ISymbol> _writtenInside; private ImmutableArray<ISymbol> _readOutside; private ImmutableArray<ISymbol> _writtenOutside; private ImmutableArray<ISymbol> _captured; private ImmutableArray<IMethodSymbol> _usedLocalFunctions; private ImmutableArray<ISymbol> _capturedInside; private ImmutableArray<ISymbol> _capturedOutside; private ImmutableArray<ISymbol> _unsafeAddressTaken; private HashSet<PrefixUnaryExpressionSyntax> _unassignedVariableAddressOfSyntaxes; private bool? _succeeded; internal CSharpDataFlowAnalysis(RegionAnalysisContext context) { _context = context; } /// <summary> /// A collection of the local variables that are declared within the region. Note that the region must be /// bounded by a method's body or a field's initializer, so method parameter symbols are never included /// in the result, but lambda parameters might appear in the result. /// </summary> public override ImmutableArray<ISymbol> VariablesDeclared { // Variables declared in the region is computed by a simple scan. // ISSUE: are these only variables declared at the top level in the region, // or are we to include variables declared in deeper scopes within the region? get { if (_variablesDeclared.IsDefault) { var result = Succeeded ? Normalize(VariablesDeclaredWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _variablesDeclared, result); } return _variablesDeclared; } } private HashSet<Symbol> UnassignedVariables { get { if (_unassignedVariables == null) { var result = Succeeded ? UnassignedVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet<Symbol>(); Interlocked.CompareExchange(ref _unassignedVariables, result, null); } return _unassignedVariables; } } /// <summary> /// A collection of the local variables for which a value assigned outside the region may be used inside the region. /// </summary> public override ImmutableArray<ISymbol> DataFlowsIn { get { if (_dataFlowsIn.IsDefault) { _succeeded = !_context.Failed; var result = _context.Failed ? ImmutableArray<ISymbol>.Empty : Normalize(DataFlowsInWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, UnassignedVariableAddressOfSyntaxes, out _succeeded)); ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsIn, result); } return _dataFlowsIn; } } /// <summary> /// The set of local variables which are definitely assigned a value when a region is /// entered. /// </summary> public override ImmutableArray<ISymbol> DefinitelyAssignedOnEntry => ComputeDefinitelyAssignedValues().onEntry; /// <summary> /// The set of local variables which are definitely assigned a value when a region is /// exited. /// </summary> public override ImmutableArray<ISymbol> DefinitelyAssignedOnExit => ComputeDefinitelyAssignedValues().onExit; private (ImmutableArray<ISymbol> onEntry, ImmutableArray<ISymbol> onExit) ComputeDefinitelyAssignedValues() { // Check for _definitelyAssignedOnExit as that's the last thing we write to. If it's not // Default, then we'll have written to both variables and can safely read from either of // them. if (_definitelyAssignedOnExit.IsDefault) { var entryResult = ImmutableArray<ISymbol>.Empty; var exitResult = ImmutableArray<ISymbol>.Empty; if (Succeeded) { var (entry, exit) = DefinitelyAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion); entryResult = Normalize(entry); exitResult = Normalize(exit); } ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnEntry, entryResult); ImmutableInterlocked.InterlockedInitialize(ref _definitelyAssignedOnExit, exitResult); } return (_definitelyAssignedOnEntry, _definitelyAssignedOnExit); } /// <summary> /// A collection of the local variables for which a value assigned inside the region may be used outside the region. /// Note that every reachable assignment to a ref or out variable will be included in the results. /// </summary> public override ImmutableArray<ISymbol> DataFlowsOut { get { var discarded = DataFlowsIn; // force DataFlowsIn to be computed if (_dataFlowsOut.IsDefault) { var result = Succeeded ? Normalize(DataFlowsOutWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariables, _dataFlowsIn)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _dataFlowsOut, result); } return _dataFlowsOut; } } /// <summary> /// A collection of the local variables for which a value is always assigned inside the region. /// </summary> public override ImmutableArray<ISymbol> AlwaysAssigned { get { if (_alwaysAssigned.IsDefault) { var result = Succeeded ? Normalize(AlwaysAssignedWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion)) : ImmutableArray<ISymbol>.Empty; ImmutableInterlocked.InterlockedInitialize(ref _alwaysAssigned, result); } return _alwaysAssigned; } } /// <summary> /// A collection of the local variables that are read inside the region. /// </summary> public override ImmutableArray<ISymbol> ReadInside { get { if (_readInside.IsDefault) { AnalyzeReadWrite(); } return _readInside; } } /// <summary> /// A collection of local variables that are written inside the region. /// </summary> public override ImmutableArray<ISymbol> WrittenInside { get { if (_writtenInside.IsDefault) { AnalyzeReadWrite(); } return _writtenInside; } } /// <summary> /// A collection of the local variables that are read outside the region. /// </summary> public override ImmutableArray<ISymbol> ReadOutside { get { if (_readOutside.IsDefault) { AnalyzeReadWrite(); } return _readOutside; } } /// <summary> /// A collection of local variables that are written outside the region. /// </summary> public override ImmutableArray<ISymbol> WrittenOutside { get { if (_writtenOutside.IsDefault) { AnalyzeReadWrite(); } return _writtenOutside; } } private void AnalyzeReadWrite() { IEnumerable<Symbol> readInside, writtenInside, readOutside, writtenOutside, captured, unsafeAddressTaken, capturedInside, capturedOutside; IEnumerable<MethodSymbol> usedLocalFunctions; if (Succeeded) { ReadWriteWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode, _context.FirstInRegion, _context.LastInRegion, UnassignedVariableAddressOfSyntaxes, readInside: out readInside, writtenInside: out writtenInside, readOutside: out readOutside, writtenOutside: out writtenOutside, captured: out captured, unsafeAddressTaken: out unsafeAddressTaken, capturedInside: out capturedInside, capturedOutside: out capturedOutside, usedLocalFunctions: out usedLocalFunctions); } else { readInside = writtenInside = readOutside = writtenOutside = captured = unsafeAddressTaken = capturedInside = capturedOutside = Enumerable.Empty<Symbol>(); usedLocalFunctions = Enumerable.Empty<MethodSymbol>(); } ImmutableInterlocked.InterlockedInitialize(ref _readInside, Normalize(readInside)); ImmutableInterlocked.InterlockedInitialize(ref _writtenInside, Normalize(writtenInside)); ImmutableInterlocked.InterlockedInitialize(ref _readOutside, Normalize(readOutside)); ImmutableInterlocked.InterlockedInitialize(ref _writtenOutside, Normalize(writtenOutside)); ImmutableInterlocked.InterlockedInitialize(ref _captured, Normalize(captured)); ImmutableInterlocked.InterlockedInitialize(ref _capturedInside, Normalize(capturedInside)); ImmutableInterlocked.InterlockedInitialize(ref _capturedOutside, Normalize(capturedOutside)); ImmutableInterlocked.InterlockedInitialize(ref _unsafeAddressTaken, Normalize(unsafeAddressTaken)); ImmutableInterlocked.InterlockedInitialize(ref _usedLocalFunctions, Normalize(usedLocalFunctions)); } /// <summary> /// A collection of the non-constant local variables and parameters that have been referenced in anonymous functions /// and therefore must be moved to a field of a frame class. /// </summary> public override ImmutableArray<ISymbol> Captured { get { if (_captured.IsDefault) { AnalyzeReadWrite(); } return _captured; } } public override ImmutableArray<ISymbol> CapturedInside { get { if (_capturedInside.IsDefault) { AnalyzeReadWrite(); } return _capturedInside; } } public override ImmutableArray<ISymbol> CapturedOutside { get { if (_capturedOutside.IsDefault) { AnalyzeReadWrite(); } return _capturedOutside; } } /// <summary> /// A collection of the non-constant local variables and parameters that have had their address (or the address of one /// of their fields) taken using the '&amp;' operator. /// </summary> /// <remarks> /// If there are any of these in the region, then a method should not be extracted. /// </remarks> public override ImmutableArray<ISymbol> UnsafeAddressTaken { get { if (_unsafeAddressTaken.IsDefault) { AnalyzeReadWrite(); } return _unsafeAddressTaken; } } public override ImmutableArray<IMethodSymbol> UsedLocalFunctions { get { if (_usedLocalFunctions.IsDefault) { AnalyzeReadWrite(); } return _usedLocalFunctions; } } private HashSet<PrefixUnaryExpressionSyntax> UnassignedVariableAddressOfSyntaxes { get { if (_unassignedVariableAddressOfSyntaxes == null) { var result = Succeeded ? UnassignedAddressTakenVariablesWalker.Analyze(_context.Compilation, _context.Member, _context.BoundNode) : new HashSet<PrefixUnaryExpressionSyntax>(); Interlocked.CompareExchange(ref _unassignedVariableAddressOfSyntaxes, result, null); } return _unassignedVariableAddressOfSyntaxes; } } /// <summary> /// Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression, /// a single statement, or a contiguous series of statements within the enclosing block. /// </summary> public sealed override bool Succeeded { get { if (_succeeded == null) { var discarded = DataFlowsIn; } return _succeeded.Value; } } private static ImmutableArray<ISymbol> Normalize(IEnumerable<Symbol> data) { return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).GetPublicSymbols()); } private static ImmutableArray<IMethodSymbol> Normalize(IEnumerable<MethodSymbol> data) { return ImmutableArray.CreateRange(data.Where(s => s.CanBeReferencedByName).OrderBy(s => s, LexicalOrderSymbolComparer.Instance).Select(p => p.GetPublicSymbol())); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/TypeWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal struct TypeWalker { private readonly Type _type; public TypeWalker(Type type) { _type = type; } public TypeEnumerator GetEnumerator() { return new TypeEnumerator(_type); } internal struct TypeEnumerator : IDisposable { private bool _first; private ArrayBuilder<Type> _stack; public TypeEnumerator(Type type) { _first = true; _stack = ArrayBuilder<Type>.GetInstance(); _stack.Push(type); } public Type Current => _stack.Peek(); public bool MoveNext() { if (_first) { _first = false; return true; } if (_stack.Count == 0) { return false; } var curr = _stack.Pop(); if (curr.HasElementType) { _stack.Push(curr.GetElementType()); return true; } // Push children in reverse order so they get popped in forward order. var children = curr.GetGenericArguments(); var numChildren = children.Length; for (int i = numChildren - 1; i >= 0; i--) { _stack.Push(children[i]); } return _stack.Count > 0; } public void Reset() { throw new NotSupportedException(); } public void Dispose() { Debug.Assert(_stack != null); _stack.Free(); _stack = null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal struct TypeWalker { private readonly Type _type; public TypeWalker(Type type) { _type = type; } public TypeEnumerator GetEnumerator() { return new TypeEnumerator(_type); } internal struct TypeEnumerator : IDisposable { private bool _first; private ArrayBuilder<Type> _stack; public TypeEnumerator(Type type) { _first = true; _stack = ArrayBuilder<Type>.GetInstance(); _stack.Push(type); } public Type Current => _stack.Peek(); public bool MoveNext() { if (_first) { _first = false; return true; } if (_stack.Count == 0) { return false; } var curr = _stack.Pop(); if (curr.HasElementType) { _stack.Push(curr.GetElementType()); return true; } // Push children in reverse order so they get popped in forward order. var children = curr.GetGenericArguments(); var numChildren = children.Length; for (int i = numChildren - 1; i >= 0; i--) { _stack.Push(children[i]); } return _stack.Count > 0; } public void Reset() { throw new NotSupportedException(); } public void Dispose() { Debug.Assert(_stack != null); _stack.Free(); _stack = null; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Core/Portable/InternalUtilities/ConsList`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Roslyn.Utilities { /// <summary> /// a simple Lisp-like immutable list. Good to use when lists are always accessed from the head. /// </summary> internal class ConsList<T> : IEnumerable<T> { public static readonly ConsList<T> Empty = new(); private readonly T? _head; private readonly ConsList<T>? _tail; internal struct Enumerator : IEnumerator<T> { private T? _current; private ConsList<T> _tail; internal Enumerator(ConsList<T> list) { _current = default; _tail = list; } public T Current { get { Debug.Assert(_tail != null); // This never returns null after a proper call to `MoveNext` returned true. return _current!; } } public bool MoveNext() { var currentTail = _tail; var newTail = currentTail._tail; if (newTail != null) { // Suppress false positive CS8717 reported for MaybeNull assignment to AllowNull // https://github.com/dotnet/roslyn/issues/38926 _current = currentTail._head!; _tail = newTail; return true; } _current = default; return false; } public void Dispose() { } object? IEnumerator.Current { get { return this.Current; } } public void Reset() { throw new NotSupportedException(); } } private ConsList() { _head = default; _tail = null; } public ConsList(T head, ConsList<T> tail) { Debug.Assert(tail != null); _head = head; _tail = tail; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Head { get { Debug.Assert(this != Empty); return _head!; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ConsList<T> Tail { get { Debug.Assert(this != Empty); RoslynDebug.Assert(_tail is object); return _tail; } } public bool Any() { return this != Empty; } public ConsList<T> Push(T value) { return new ConsList<T>(value, this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } public Enumerator GetEnumerator() { return new Enumerator(this); } public override string ToString() { StringBuilder result = new StringBuilder("ConsList["); bool any = false; for (ConsList<T> list = this; list._tail != null; list = list._tail) { if (any) { result.Append(", "); } result.Append(list.Head); any = true; } result.Append("]"); return result.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. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Roslyn.Utilities { /// <summary> /// a simple Lisp-like immutable list. Good to use when lists are always accessed from the head. /// </summary> internal class ConsList<T> : IEnumerable<T> { public static readonly ConsList<T> Empty = new(); private readonly T? _head; private readonly ConsList<T>? _tail; internal struct Enumerator : IEnumerator<T> { private T? _current; private ConsList<T> _tail; internal Enumerator(ConsList<T> list) { _current = default; _tail = list; } public T Current { get { Debug.Assert(_tail != null); // This never returns null after a proper call to `MoveNext` returned true. return _current!; } } public bool MoveNext() { var currentTail = _tail; var newTail = currentTail._tail; if (newTail != null) { // Suppress false positive CS8717 reported for MaybeNull assignment to AllowNull // https://github.com/dotnet/roslyn/issues/38926 _current = currentTail._head!; _tail = newTail; return true; } _current = default; return false; } public void Dispose() { } object? IEnumerator.Current { get { return this.Current; } } public void Reset() { throw new NotSupportedException(); } } private ConsList() { _head = default; _tail = null; } public ConsList(T head, ConsList<T> tail) { Debug.Assert(tail != null); _head = head; _tail = tail; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Head { get { Debug.Assert(this != Empty); return _head!; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ConsList<T> Tail { get { Debug.Assert(this != Empty); RoslynDebug.Assert(_tail is object); return _tail; } } public bool Any() { return this != Empty; } public ConsList<T> Push(T value) { return new ConsList<T>(value, this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } public Enumerator GetEnumerator() { return new Enumerator(this); } public override string ToString() { StringBuilder result = new StringBuilder("ConsList["); bool any = false; for (ConsList<T> list = this; list._tail != null; list = list._tail) { if (any) { result.Append(", "); } result.Append(list.Head); any = true; } result.Append("]"); return result.ToString(); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./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
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensTests.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 enable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens { public class SemanticTokensTests : AbstractSemanticTokensTests { [Fact] public async Task TestGetSemanticTokensAsync() { var markup = @"{|caret:|}// Comment static class C { }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } /// <summary> /// Tests all three handlers in succession and makes sure we receive the expected result at each stage. /// </summary> [Fact] public async Task TestAllHandlersAsync() { var markup = @"{|caret:|}// Comment static class C { } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].First(); // 1. Range handler var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) }; var rangeResults = await RunGetSemanticTokensRangeAsync(testLspServer, caretLocation, range); var expectedRangeResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, rangeResults.Data!).ConfigureAwait(false); Assert.Equal(expectedRangeResults.Data, rangeResults.Data); Assert.Equal(expectedRangeResults.ResultId, rangeResults.ResultId); Assert.True(rangeResults is RoslynSemanticTokens); // 2. Whole document handler var wholeDocResults = await RunGetSemanticTokensAsync(testLspServer, caretLocation); var expectedWholeDocResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "2" }; await VerifyNoMultiLineTokens(testLspServer, wholeDocResults.Data!).ConfigureAwait(false); Assert.Equal(expectedWholeDocResults.Data, wholeDocResults.Data); Assert.Equal(expectedWholeDocResults.ResultId, wholeDocResults.ResultId); Assert.True(wholeDocResults is RoslynSemanticTokens); // 3. Edits handler - insert newline at beginning of file var newMarkup = @" // Comment static class C { } "; UpdateDocumentText(newMarkup, testLspServer.TestWorkspace); var editResults = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "2"); var expectedEdit = new LSP.SemanticTokensEdit { Start = 0, DeleteCount = 1, Data = new int[] { 1 } }; Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)editResults).Edits.First()); Assert.Equal("3", ((LSP.SemanticTokensDelta)editResults).ResultId); Assert.True((LSP.SemanticTokensDelta)editResults is RoslynSemanticTokensDelta); // 4. Edits handler - no changes (ResultId should remain same) var editResultsNoChange = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "3"); Assert.Equal("3", ((LSP.SemanticTokensDelta)editResultsNoChange).ResultId); Assert.True((LSP.SemanticTokensDelta)editResultsNoChange is RoslynSemanticTokensDelta); // 5. Re-request whole document handler (may happen if LSP runs into an error) var wholeDocResults2 = await RunGetSemanticTokensAsync(testLspServer, caretLocation); var expectedWholeDocResults2 = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "4" }; await VerifyNoMultiLineTokens(testLspServer, wholeDocResults2.Data!).ConfigureAwait(false); Assert.Equal(expectedWholeDocResults2.Data, wholeDocResults2.Data); Assert.Equal(expectedWholeDocResults2.ResultId, wholeDocResults2.ResultId); Assert.True(wholeDocResults2 is RoslynSemanticTokens); } [Fact] public async Task TestGetSemanticTokensMultiLineCommentAsync() { var markup = @"{|caret:|}class C { /* one two three */ } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '/* one' 1, 0, 3, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'two' 1, 0, 8, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'three */' 0, 9, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } [Fact] public async Task TestGetSemanticTokensStringLiteralAsync() { var markup = @"{|caret:|}class C { void M() { var x = @""one two """" three""; } } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C' 1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 1, 4, 4, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'void' 0, 5, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.MethodName], 0, // 'M' 0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '(' 0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ')' 1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 1, 8, 3, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Keyword], 0, // 'var' 0, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.LocalName], 0, // 'x' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Operator], 0, // '=' 0, 2, 5, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // '@"one' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'two' 0, 4, 2, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.StringEscapeCharacter], 0, // '""' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'three"' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ';' 1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' 1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } } }
// Licensed to the .NET Foundation under one or more 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 enable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens { public class SemanticTokensTests : AbstractSemanticTokensTests { [Fact] public async Task TestGetSemanticTokensAsync() { var markup = @"{|caret:|}// Comment static class C { }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } /// <summary> /// Tests all three handlers in succession and makes sure we receive the expected result at each stage. /// </summary> [Fact] public async Task TestAllHandlersAsync() { var markup = @"{|caret:|}// Comment static class C { } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].First(); // 1. Range handler var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) }; var rangeResults = await RunGetSemanticTokensRangeAsync(testLspServer, caretLocation, range); var expectedRangeResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, rangeResults.Data!).ConfigureAwait(false); Assert.Equal(expectedRangeResults.Data, rangeResults.Data); Assert.Equal(expectedRangeResults.ResultId, rangeResults.ResultId); Assert.True(rangeResults is RoslynSemanticTokens); // 2. Whole document handler var wholeDocResults = await RunGetSemanticTokensAsync(testLspServer, caretLocation); var expectedWholeDocResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "2" }; await VerifyNoMultiLineTokens(testLspServer, wholeDocResults.Data!).ConfigureAwait(false); Assert.Equal(expectedWholeDocResults.Data, wholeDocResults.Data); Assert.Equal(expectedWholeDocResults.ResultId, wholeDocResults.ResultId); Assert.True(wholeDocResults is RoslynSemanticTokens); // 3. Edits handler - insert newline at beginning of file var newMarkup = @" // Comment static class C { } "; UpdateDocumentText(newMarkup, testLspServer.TestWorkspace); var editResults = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "2"); var expectedEdit = new LSP.SemanticTokensEdit { Start = 0, DeleteCount = 1, Data = new int[] { 1 } }; Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)editResults).Edits.First()); Assert.Equal("3", ((LSP.SemanticTokensDelta)editResults).ResultId); Assert.True((LSP.SemanticTokensDelta)editResults is RoslynSemanticTokensDelta); // 4. Edits handler - no changes (ResultId should remain same) var editResultsNoChange = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "3"); Assert.Equal("3", ((LSP.SemanticTokensDelta)editResultsNoChange).ResultId); Assert.True((LSP.SemanticTokensDelta)editResultsNoChange is RoslynSemanticTokensDelta); // 5. Re-request whole document handler (may happen if LSP runs into an error) var wholeDocResults2 = await RunGetSemanticTokensAsync(testLspServer, caretLocation); var expectedWholeDocResults2 = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "4" }; await VerifyNoMultiLineTokens(testLspServer, wholeDocResults2.Data!).ConfigureAwait(false); Assert.Equal(expectedWholeDocResults2.Data, wholeDocResults2.Data); Assert.Equal(expectedWholeDocResults2.ResultId, wholeDocResults2.ResultId); Assert.True(wholeDocResults2 is RoslynSemanticTokens); } [Fact] public async Task TestGetSemanticTokensMultiLineCommentAsync() { var markup = @"{|caret:|}class C { /* one two three */ } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '/* one' 1, 0, 3, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'two' 1, 0, 8, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'three */' 0, 9, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } [Fact] public async Task TestGetSemanticTokensStringLiteralAsync() { var markup = @"{|caret:|}class C { void M() { var x = @""one two """" three""; } } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First()); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C' 1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 1, 4, 4, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'void' 0, 5, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.MethodName], 0, // 'M' 0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '(' 0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ')' 1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 1, 8, 3, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Keyword], 0, // 'var' 0, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.LocalName], 0, // 'x' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Operator], 0, // '=' 0, 2, 5, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // '@"one' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'two' 0, 4, 2, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.StringEscapeCharacter], 0, // '""' 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'three"' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ';' 1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' 1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharpTest/Structure/IndexerDeclarationStructureTests.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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class IndexerDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<IndexerDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new IndexerDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer1() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer2() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} int Value => 0; }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer3() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} int Value => 0; }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexerWithComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$public string this[int index]{|textspan2: { get { } }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexerWithWithExpressionBodyAndComments() { const string code = @" class C { {|span:// Goo // Bar|} $$public string this[int index] => 0; }"; await VerifyBlockSpansAsync(code, Region("span", "// Goo ...", 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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class IndexerDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<IndexerDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new IndexerDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer1() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer2() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} int Value => 0; }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexer3() { const string code = @" class C { {|hint:$$public string this[int index]{|textspan: { get { } }|}|} int Value => 0; }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexerWithComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$public string this[int index]{|textspan2: { get { } }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndexerWithWithExpressionBodyAndComments() { const string code = @" class C { {|span:// Goo // Bar|} $$public string this[int index] => 0; }"; await VerifyBlockSpansAsync(code, Region("span", "// Goo ...", autoCollapse: true)); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IArgument.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IArgument : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoArgument() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2() { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgument() { string source = @" class P { static void M1() { /*<bind>*/M2(1, 2.0)/*</bind>*/; } static void M2(int x, double y) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, System.Double y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 2.0)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '2.0') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2(1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentListedInParameterOrder() { string source = @" class P { static void M1() { /*<bind>*/M2(x: 1, y: 9.9)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x: 1, y: 9.9)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 9.9') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 9.9) (Syntax: '9.9') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentListedOutOfParameterOrder() { string source = @" class P { static void M1() { /*<bind>*/M2(y: 9.9, x: 1)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: 9.9, x: 1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 9.9') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 9.9) (Syntax: '9.9') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentInParameterOrderWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(y: 0, z: 2)/*</bind>*/; } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: 0, z: 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(y: 0, z: 2)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(y: 0, z: 2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentOutOfParameterOrderWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(z: 2, x: 9)/*</bind>*/; } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(z: 2, x: 9)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 9') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(z: 2, x: 9)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(z: 2, x: 9)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedAndPositionalArgumentsWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(9, z: 10);/*</bind>*/ } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(9, z: 10);') Expression: IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(9, z: 10)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '9') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') 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.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(9, z: 10)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(9, z: 10)') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalRefAndOutArguments() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(ref a, out b)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(ref a, out b)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedRefAndOutArgumentsInParameterOrder() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(x: ref a, y: out b)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x: ref a, y: out b)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedRefAndOutArgumentsOutOfParameterOrder() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(y: out b, x: ref a)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: out b, x: ref a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfNewStruct() { string source = @" class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(S sobj = new S()) { } } struct S { } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([S sobj = default(S)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: sobj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfDefaultStruct() { string source = @" class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(S sobj = default(S)) { } } struct S { } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([S sobj = default(S)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: sobj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfConstant() { string source = @" class P { const double Pi = 3.14; void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(double s = Pi) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Double s = 3.14])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 3.14, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(1, 2)/*</bind>*/; } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(1, 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentOutOfParameterOrderForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(y: 1, x: 2);/*</bind>*/ } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'this.E1(y: 1, x: 2);') Expression: IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(y: 1, x: 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentWithDefaultValueForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(y: 1)/*</bind>*/; } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(y: 1)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this.E1(y: 1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'this.E1(y: 1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(1, a)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(1, 0.1, 0.2)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 0.1, 0.2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0.1) (Syntax: '0.1') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0.2) (Syntax: '0.2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInExpandedFormWithNoArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(1)') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndParamsArrayArgumentInExpandedFormWithNoArgument() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2()/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2()') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2()') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2()') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndNamedParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(array: a)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: a)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(array: a)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndNamedParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(array: 1)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(array: 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(array: 1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(array: 1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentAndNamedParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(1, array: a)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, array: a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentAndNamedParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(1, array: 1)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, array: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, array: 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1, array: 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1, array: 1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, array: 1)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentAndNamedParamsArrayArgumentInNormalFormOutOfParameterOrder() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(array: a, x: 1);/*</bind>*/ } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(array: a, x: 1);') Expression: IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: a, x: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentAndNamedParamsArrayArgumentInExpandedFormOutOfParameterOrder() { string source = @" class P { void M1() { /*<bind>*/M2(array: 1, x: 10)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: 1, x: 10)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInMethod() { string source = @" using System.Runtime.CompilerServices; class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""M1"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInProperty() { string source = @" using System.Runtime.CompilerServices; class P { bool M1 => /*<bind>*/M2()/*</bind>*/; bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation ( System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""M1"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInFieldInitializer() { string source = @" using System.Runtime.CompilerServices; class P { bool field = /*<bind>*/M2()/*</bind>*/; static bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation (System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""field"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInEventMethods() { string source = @" using System; using System.Runtime.CompilerServices; class P { public event EventHandler MyEvent { add { /*<bind>*/M2()/*</bind>*/; } remove { M2(); } } static bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation (System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""MyEvent"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [Fact] public void DefaultArgument_CallerInfo_BadParameterType() { var source0 = @" using System.Runtime.CompilerServices; public class C0 { public static void M0([CallerLineNumber] string s = ""hello"") { } // 1 } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; // 2 } } "; var expectedOperationTree = @" IInvocationOperation (void C0.M0([System.String s = ""hello""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') 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 expectedDiagnostics0And1 = new[] { // (6,28): error CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type 'int' to type 'string' // public static void M0([CallerLineNumber] string s = "hello") { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForCallerLineNumberParam, "CallerLineNumber").WithArguments("int", "string").WithLocation(6, 28), // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' // /*<bind>*/C0.M0()/*</bind>*/; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19), }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(CreateCompilation(new[] { source1, source0 }), expectedOperationTree, expectedDiagnostics0And1); var expectedDiagnostics1 = new[] { // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' // /*<bind>*/C0.M0()/*</bind>*/; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19) }; var lib0 = CreateCompilation(source0).ToMetadataReference(); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(CreateCompilation(new[] { source1 }, references: new[] { lib0 }), expectedOperationTree, expectedDiagnostics1); CreateCompilation(new[] { source1 }, references: new[] { lib0 }).VerifyEmitDiagnostics(expectedDiagnostics1); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ExtraArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1, 2)/*</bind>*/; } void M2(int x = 0) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1, 2)') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'M2' takes 2 arguments // /*<bind>*/M2(1, 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "M2").WithArguments("M2", "2").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestOmittedArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1,)/*</bind>*/; } void M2(int y, int x = 0) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1,)') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,24): error CS1525: Invalid expression term ')' // /*<bind>*/M2(1,)/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void WrongArgumentType() { string source = @" class P { void M1() { /*<bind>*/M2(1)/*</bind>*/; } void M2(string x ) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS1503: Argument 1: cannot convert from 'int' to 'string' // /*<bind>*/M2(1)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(6, 22) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VarArgsCall() { string source = @" using System; public class P { void M() { /*<bind>*/Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5))/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation (void System.Console.Write(System.String format, System.Object arg0, System.Object arg1, System.Object arg2, System.Object arg3, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... arglist(5))') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: format) (OperationKind.Argument, Type: null) (Syntax: '""{0} {1} {2} {3} {4}""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{0} {1} {2} {3} {4}"") (Syntax: '""{0} {1} {2} {3} {4}""') 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.Explicit, Matching Parameter: arg0) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.Explicit, Matching Parameter: arg3) (OperationKind.Argument, Type: null) (Syntax: '4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(5)') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(5)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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<InvocationExpressionSyntax>(source, expectedOperationTree, TargetFramework.Mscorlib45, expectedDiagnostics); } /// <summary> /// See <see cref="InvalidConversionForDefaultArgument_InIL" /> for a similar scenario for involving a bad constant value from metadata. /// </summary> [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_InSource() { var source0 = @" public class C0 { public static void M0(int x = ""string"") { } // 1 } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Parameter default values in source produce ConstantValue.Bad when they fail to convert to the parameter type, // and when we use that to create a default argument, we just fall back to default(ParameterType). // This has the effect of reducing cascading diagnostics when a parameter default value is bad in source. // On the other hand, if `void M2(int)` came from metadata (i.e. hand-written malformed IL), we would produce a string ConstantValue for it, // and the operation tree would contain a bad conversion to int with an operand of type string. We also produce a compilation error for the bad conversion. var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.Int32 x = default(System.Int32)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'C0.M0()') 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 expectedDiagnostics0 = new DiagnosticDescription[] { // (4,31): error CS1750: A value of type 'string' cannot be used as a default parameter because there are no standard conversions to type 'int' // public static void M0(int x = "string") { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("string", "int").WithLocation(4, 31) }; var comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, expectedDiagnostics0); comp.VerifyEmitDiagnostics(expectedDiagnostics0); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(expectedDiagnostics0); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ValidConversionForDefaultArgument_DateTime() { var source0 = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DateTimeConstant(634953547672667479L)] DateTime x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.DateTime x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') ILiteralOperation (OperationKind.Literal, Type: System.DateTime, Constant: 02/01/2013 22:32:47, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_DateTime() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DateTimeConstant(634953547672667479L)] string x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Note that DateTime constants which fail to convert to the parameter type are silently replaced with default(T). var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.String x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ValidConversionForDefaultArgument_Decimal() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] decimal x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.Decimal x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 50, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_Decimal() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] string x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Note that decimal constants which fail to convert to the parameter type are silently replaced with default(T). var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.String x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ReadingFromIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } set { _number = value; } } void M1() { var x = /*<bind>*/this[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultArgumentForIndexerGetter() { string source = @" class P { private int _number = 0; public int this[int i = 1, int j = 2] { get { return _number; } set { _number = i + j; } } void M1() { var x = /*<bind>*/this[j:10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 1], [System.Int32 j = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[j:10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: j) (OperationKind.Argument, Type: null) (Syntax: 'j:10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[j:10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'this[j:10]') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ReadingFromWriteOnlyIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { set { _number = value; } } void M1() { var x = /*<bind>*/this[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') 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[] { // file.cs(12,27): error CS0154: The property or indexer 'P.this[int]' cannot be used in this context because it lacks the get accessor // var x = /*<bind>*/this[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[10]").WithArguments("P.this[int]").WithLocation(12, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReadOnlyIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } } void M1() { /*<bind>*/this[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') 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[] { // file.cs(12,19): error CS0200: Property or indexer 'P.this[int]' cannot be assigned to -- it is read only // /*<bind>*/this[10]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[10]").WithArguments("P.this[int]").WithLocation(12, 19) }; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OverridingIndexerWithDefaultArgument() { string source = @" class Base { public virtual int this[int x = 0, int y = 1] { set { } get { System.Console.Write(y); return 0; } } } class Derived : Base { public override int this[int x = 8, int y = 9] { set { } } } internal class P { static void Main() { var d = new Derived(); var x = /*<bind>*/d[0]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 Derived.this[[System.Int32 x = 8], [System.Int32 y = 9]] { set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'd[0]') Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: Derived) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'd[0]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'd[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; string expectedOutput = @"1"; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { source }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OmittedParamArrayArgumentInIndexerAccess() { string source = @" class P { public int this[int x, params int[] y] { set { } get { return 0; } } public void M() { /*<bind>*/this[0]/*</bind>*/ = 0; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 x, params System.Int32[] y] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'this[0]') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[0]') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReturnsByRefIndexer() { string source = @" class P { ref int this[int x] { get => throw null; } public void M() { /*<bind>*/this[0]/*</bind>*/ = 0; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: ref System.Int32 P.this[System.Int32 x] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void AssigningToIndexer_UsingDefaultArgumentFromSetter() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); /*<bind>*/p[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 4 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ReadFromIndexer_UsingDefaultArgumentFromGetter() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); var x = /*<bind>*/p[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 2 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void IndexerAccess_LHSOfCompoundAssignment() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); /*<bind>*/p[10]/*</bind>*/ += 99; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 2 10 2 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] 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 void M1([opt] int32 s) cil managed { .param [1] = ""abc"" // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method P::M1 } // end of class P "; var csharp = @" class C { public void M2() { P p = new P(); /*<bind>*/p.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M1([System.Int32 s = ""abc""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'p.M1()') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P, IsInvalid) (Syntax: 'p') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'p.M1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'p.M1()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"", IsInvalid, IsImplicit) (Syntax: 'p.M1()') 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[] { // file.cs(7,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // /*<bind>*/p.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 20) }; VerifyOperationTreeAndDiagnosticsForTestWithIL<InvocationExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_Call() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(bool? x = true) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Boolean[missing]? x = true])) (OperationKind.Invocation, Type: System.Void[missing], IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'M2()') 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[] { // (4,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(4, 12), // (9,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 20), // (9,20): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 20), // (9,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(9, 12), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (9,30): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "true").WithArguments("System.Boolean").WithLocation(9, 30), // (6,19): error CS0518: Predefined type 'System.Object' is not defined or imported // /*<bind>*/M2()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "M2").WithArguments("System.Object").WithLocation(6, 19), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P()/*</bind>*/; } P(bool? x = true) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor([System.Boolean[missing]? x = true])) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'new P()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: '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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,12): error CS0518: Predefined type 'System.Object' is not defined or imported // static P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(4, 12), // (9,7): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 7), // (9,7): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 7), // (9,5): error CS0518: Predefined type 'System.Void' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"P(bool? x = true) { }").WithArguments("System.Void").WithLocation(9, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (9,17): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "true").WithArguments("System.Boolean").WithLocation(9, 17), // (6,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(6, 30), // (9,5): error CS1729: 'object' does not contain a constructor that takes 0 arguments // P(bool? x = true) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(9, 5) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_Indexer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = 5] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = 5]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'this[0]') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[0]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 5, IsInvalid, IsImplicit) (Syntax: 'this[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[] { // (5,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 13), // (6,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 12), // (6,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 21), // (6,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 28), // (6,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(6, 28), // (9,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(9, 9), // (12,5): error CS0518: Predefined type 'System.Void' is not defined or imported // void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(12, 5), // (3,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(3, 7), // (6,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "5").WithArguments("System.Int32").WithLocation(6, 37), // (5,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(5, 27), // (14,24): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(14, 24), // (14,40): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "9").WithArguments("System.Int32").WithLocation(14, 40), // (3,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(3, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_Call() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(bool? x = null) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Boolean[missing]? x = null])) (OperationKind.Invocation, Type: System.Void[missing], IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') 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[] { // (4,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(4, 12), // (9,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 20), // (9,20): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 20), // (9,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(9, 12), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (6,19): error CS0518: Predefined type 'System.Object' is not defined or imported // /*<bind>*/M2()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "M2").WithArguments("System.Object").WithLocation(6, 19), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P()/*</bind>*/; } P(bool? x = null) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor([System.Boolean[missing]? x = null])) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'new P()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: '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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,12): error CS0518: Predefined type 'System.Object' is not defined or imported // static P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(4, 12), // (9,7): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 7), // (9,7): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 7), // (9,5): error CS0518: Predefined type 'System.Void' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"P(bool? x = null) { }").WithArguments("System.Void").WithLocation(9, 5), // (6,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(6, 30), // (9,5): error CS1729: 'object' does not contain a constructor that takes 0 arguments // P(bool? x = null) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(9, 5) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_Indexer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = null] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'this[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[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[] { // (16,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(16, 1), // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Void' is not defined or imported // void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,24): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 24), // (13,40): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "9").WithArguments("System.Int32").WithLocation(13, 40), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueWithParameterErrorType_Call() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, S s = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [S s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,27): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, S s = 0) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 27), // file.cs(9,29): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // static void M2(int x, S s = 0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 29) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<InvocationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P(1)/*</bind>*/; } P(int x, S s = 0) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor(System.Int32 x, [S s = null])) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(1)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'new P(1)') 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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,14): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // P(int x, S s = 0) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 14), // file.cs(9,16): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // P(int x, S s = 0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 16) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ObjectCreationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_Indexer() { string source = @" class P { private int _number = 0; public int this[int index, S s = 0] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index, [S s = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'this[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[] { // file.cs(5,32): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // public int this[int index, S s = 0] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(5, 32), // file.cs(5,34): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public int this[int index, S s = 0] Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 34) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ElementAccessExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18722, "https://github.com/dotnet/roslyn/issues/18722")] public void DefaultValueForGenericWithUndefinedTypeArgument() { // TODO: https://github.com/dotnet/roslyn/issues/18722 // This should be treated as invalid invocation. string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, G<S> s = null) { } } class G<T> { } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [G<S> s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: G<S>, Constant: null, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,29): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, G<S> s = null) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18722, "https://github.com/dotnet/roslyn/issues/18722")] public void DefaultValueForNullableGenericWithUndefinedTypeArgument() { // TODO: https://github.com/dotnet/roslyn/issues/18722 // This should be treated as invalid invocation. string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, G<S>? s = null) { } } struct G<T> { } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [G<S>? s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: G<S>?, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,29): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, G<S> s = null) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void GettingInOutConversionFromCSharpArgumentShouldThrowException() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x) { } } "; var compilation = CreateCompilation(source); var (operation, syntaxNode) = GetOperationAndSyntaxForTest<InvocationExpressionSyntax>(compilation); var invocation = (IInvocationOperation)operation; var argument = invocation.Arguments[0]; // We are calling VB extension methods on IArgument in C# code, therefore exception is expected here. Assert.Throws<ArgumentException>(() => argument.GetInConversion()); Assert.Throws<ArgumentException>(() => argument.GetOutConversion()); } [Fact] public void DirectlyBindArgument_InvocationExpression() { string source = @" class P { static void M1() { M2(/*<bind>*/1/*</bind>*/); } static void M2(int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindRefArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; M2(/*<bind>*/ref i/*</bind>*/); } static void M2(ref int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'ref i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindInArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; ref int refI = ref i; M2(/*<bind>*/refI/*</bind>*/); } static void M2(in int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'refI') ILocalReferenceOperation: refI (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'refI') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindOutArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; M2(/*<bind>*/out i/*</bind>*/); } static void M2(out int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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[] { // CS0177: The out parameter 'i' must be assigned to before control leaves the current method // static void M2(out int i) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "M2").WithArguments("i").WithLocation(9, 17) }; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_InvocationExpression() { string source = @" class P { static void M1() { /*<bind>*/M2(1);/*</bind>*/ } static void M2(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1);') Expression: IInvocationOperation (void P.M2(params System.Int32[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'M2(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_InvocationExpression() { string source = @" class P { static void M1() { /*<bind>*/M2(0, 1);/*</bind>*/ } static void M2(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(0, 1);') Expression: IInvocationOperation (void P.M2(params System.Int32[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(0, 1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(0, 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'M2(0, 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(0, 1)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(0, 1)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindNamedArgument1_InvocationExpression() { string source = @" class P { static void M1() { M2(/*<bind>*/j: 1/*</bind>*/, i: 1); } static void M2(int i, int j) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: j) (OperationKind.Argument, Type: null) (Syntax: 'j: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindNamedArgument2_InvocationExpression() { string source = @" class P { static void M1() { M2(j: 1, /*<bind>*/i: 1/*</bind>*/); } static void M2(int i, int j) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_ObjectCreation() { string source = @" class P { static void M1() { new P(/*<bind>*/1/*</bind>*/); } public P(int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindRefArgument_ObjectCreation() { string source = @" class P { static void M1() { int i = 0; new P(/*<bind>*/ref i/*</bind>*/); } public P(ref int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'ref i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindOutArgument_ObjectCreation() { string source = @" class P { static void M1() { int i = 0; new P(/*<bind>*/out i/*</bind>*/); } public P(out int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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[] { // CS0177: The out parameter 'i' must be assigned to before control leaves the current method // public P(out int i) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "P").WithArguments("i").WithLocation(9, 12) }; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_ObjectCreation() { string source = @" class P { static void M1() { /*<bind>*/new P(1);/*</bind>*/ } public P(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'new P(1);') Expression: IObjectCreationOperation (Constructor: P..ctor(params System.Int32[] array)) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(1)') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'new P(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new P(1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'new P(1)') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_ObjectCreation() { string source = @" class P { static void M1() { /*<bind>*/new P(0, 1);/*</bind>*/ } public P(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'new P(0, 1);') Expression: IObjectCreationOperation (Constructor: P..ctor(params System.Int32[] array)) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(0, 1)') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(0, 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'new P(0, 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new P(0, 1)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'new P(0, 1)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_Indexer() { string source = @" class P { void M1() { var v = this[/*<bind>*/1/*</bind>*/]; } public int this[int i] => 0; } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_Indexer() { string source = @" class P { void M1() { var v = /*<bind>*/this[1]/*</bind>*/; } public int this[params int[] array] => 0; } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[params System.Int32[] array] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[1]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[1]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'this[1]') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[1]') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_Indexer() { string source = @" class P { void M1() { var v = /*<bind>*/this[0, 1]/*</bind>*/; } public int this[params int[] array] => 0; } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[params System.Int32[] array] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0, 1]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0, 1]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[0, 1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'this[0, 1]') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[0, 1]') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_Attribute() { string source = @" [assembly: /*<bind>*/System.CLSCompliant(isCompliant: true)/*</bind>*/] "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: 'System.CLSC ... iant: true)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AttributeSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument2_Attribute() { string source = @" [assembly: MyA(/*<bind>*/Prop = ""test""/*</bind>*/)] class MyA : System.Attribute { public string Prop {get;set;} } "; string expectedOperationTree = @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'Prop = ""test""') Left: IPropertyReferenceOperation: System.String MyA.Prop { get; set; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Prop') Instance Receiver: null Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: '""test""') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AttributeArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_NonTrailingNamedArgument() { string source = @" class P { void M1(int i, int i2) { M1(i: 0, /*<bind>*/2/*</bind>*/); } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NonNullDefaultValueForNullableParameterType() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(int? x = 10) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32? x = 10])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Theory] [InlineData("null")] [InlineData("default")] [InlineData("default(int?)")] public void NullDefaultValueForNullableParameterType(string defaultValue) { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(int? x = " + defaultValue + @") { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32? x = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReadOnlyIndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '[0] = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: '[0]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(12,36): error CS0200: Property or indexer 'P.this[int]' cannot be assigned to -- it is read only // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "[0]").WithArguments("P.this[int]").WithLocation(12, 36) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void WrongSignatureIndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[string name] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '[0] = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: '[0]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,37): error CS1503: Argument 1: cannot convert from 'int' to 'string' // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "0").WithArguments("1", "int", "string").WithLocation(13, 37) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = 0] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Children(1): IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[missing], IsInvalid) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = 0]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '[0]') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[0]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Object' is not defined or imported // P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (5,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(5, 37), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(13, 30), // (13,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 37), // (13,42): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32").WithLocation(13, 42), // (13,30): error CS0518: Predefined type 'System.Void' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Void").WithLocation(13, 30), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = null] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Children(1): IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[missing], IsInvalid) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Object' is not defined or imported // P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(13, 30), // (13,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 37), // (13,42): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32").WithLocation(13, 42), // (13,30): error CS0518: Predefined type 'System.Void' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Void").WithLocation(13, 30), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, S s = 0] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32 P.this[System.Int32 x, [S s = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,28): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // public int this[int x, S s = 0] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(5, 28), // file.cs(5,30): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public int this[int x, S s = 0] Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 30) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ObjectCreationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNullableDefaultArgument() { string source = @" public struct MyStruct { static void M1(MyStruct? s = default(MyStruct)) { } // 1 static void M2() { /*<bind>*/M1();/*</bind>*/ } } "; // Note that we fall back to a literal 'null' argument here because it's our general handling for bad default parameter values in source. string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1();') Expression: IInvocationOperation (void MyStruct.M1([MyStruct? s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M1()') IDefaultValueOperation (OperationKind.DefaultValue, Type: MyStruct?, IsImplicit) (Syntax: 'M1()') 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[] { // (4,30): error CS1770: A value of type 'MyStruct' cannot be used as default parameter for nullable parameter 's' because 'MyStruct' is not a simple type // static void M1(MyStruct? s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "s").WithArguments("MyStruct", "s").WithLocation(4, 30) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<StatementSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NullableEnumDefaultArgument_NonZeroValue() { string source = @" #nullable enable public enum E { E1 = 1 } class C { void M0(E? e = E.E1) { } void M1() { /*<bind>*/M0();/*</bind>*/ } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M0();') Expression: IInvocationOperation ( void C.M0([E? e = 1])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M0()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M0') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: e) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M0()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: E?, IsImplicit) (Syntax: 'M0()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M0()') 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 comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); var operation = VerifyOperationTreeForTest<StatementSyntax>(comp, expectedOperationTree); var conversion = operation.Descendants().OfType<IConversionOperation>().Single(); // Note that IConversionOperation.IsImplicit refers to whether the code is implicitly generated by the compiler // while CommonConversion.IsImplicit refers to whether the conversion that was generated is an implicit conversion Assert.False(conversion.Conversion.IsImplicit); Assert.True(conversion.Conversion.IsNullable); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void UndefinedMethod() { string source = @" class P { static void M1() { /*<bind>*/M2(1, 2)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(1, 2)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0103: The name 'M2' does not exist in the current context // /*<bind>*/M2(1, 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "M2").WithArguments("M2").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } private class IndexerAccessArgumentVerifier : OperationWalker { private readonly Compilation _compilation; private IndexerAccessArgumentVerifier(Compilation compilation) { _compilation = compilation; } public static void Verify(IOperation operation, Compilation compilation, SyntaxNode syntaxNode) { new IndexerAccessArgumentVerifier(compilation).Visit(operation); } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { if (operation.HasErrors(_compilation) || operation.Arguments.Length == 0) { return; } // Check if the parameter symbol for argument is corresponding to indexer instead of accessor. var indexerSymbol = operation.Property; foreach (var argument in operation.Arguments) { if (!argument.HasErrors(_compilation)) { Assert.Same(indexerSymbol, argument.Parameter.ContainingSymbol); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IArgument : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoArgument() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2() { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgument() { string source = @" class P { static void M1() { /*<bind>*/M2(1, 2.0)/*</bind>*/; } static void M2(int x, double y) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, System.Double y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 2.0)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '2.0') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2(1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentListedInParameterOrder() { string source = @" class P { static void M1() { /*<bind>*/M2(x: 1, y: 9.9)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x: 1, y: 9.9)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 9.9') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 9.9) (Syntax: '9.9') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentListedOutOfParameterOrder() { string source = @" class P { static void M1() { /*<bind>*/M2(y: 9.9, x: 1)/*</bind>*/; } static void M2(int x, double y = 0.0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [System.Double y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: 9.9, x: 1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 9.9') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 9.9) (Syntax: '9.9') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentInParameterOrderWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(y: 0, z: 2)/*</bind>*/; } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: 0, z: 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(y: 0, z: 2)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(y: 0, z: 2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentOutOfParameterOrderWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(z: 2, x: 9)/*</bind>*/; } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(z: 2, x: 9)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 9') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(z: 2, x: 9)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(z: 2, x: 9)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedAndPositionalArgumentsWithDefaultValue() { string source = @" class P { static void M1() { /*<bind>*/M2(9, z: 10);/*</bind>*/ } static void M2(int x = 1, int y = 2, int z = 3) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(9, z: 10);') Expression: IInvocationOperation (void P.M2([System.Int32 x = 1], [System.Int32 y = 2], [System.Int32 z = 3])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(9, z: 10)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '9') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') 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.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z: 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(9, z: 10)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(9, z: 10)') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalRefAndOutArguments() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(ref a, out b)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(ref a, out b)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedRefAndOutArgumentsInParameterOrder() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(x: ref a, y: out b)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x: ref a, y: out b)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedRefAndOutArgumentsOutOfParameterOrder() { string source = @" class P { void M1() { int a = 1; int b; /*<bind>*/M2(y: out b, x: ref a)/*</bind>*/; } void M2(ref int x, out int y) { y = 10; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(ref System.Int32 x, out System.Int32 y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(y: out b, x: ref a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: out b') ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: ref a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfNewStruct() { string source = @" class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(S sobj = new S()) { } } struct S { } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([S sobj = default(S)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: sobj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfDefaultStruct() { string source = @" class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(S sobj = default(S)) { } } struct S { } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([S sobj = default(S)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: sobj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueOfConstant() { string source = @" class P { const double Pi = 3.14; void M1() { /*<bind>*/M2()/*</bind>*/; } void M2(double s = Pi) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Double s = 3.14])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 3.14, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(1, 2)/*</bind>*/; } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(1, 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentOutOfParameterOrderForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(y: 1, x: 2);/*</bind>*/ } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'this.E1(y: 1, x: 2);') Expression: IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(y: 1, x: 2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentWithDefaultValueForExtensionMethod() { string source = @" class P { void M1() { /*<bind>*/this.E1(y: 1)/*</bind>*/; } } static class Extensions { public static void E1(this P p, int x = 0, int y = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void Extensions.E1(this P p, [System.Int32 x = 0], [System.Int32 y = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'this.E1(y: 1)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: '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.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this.E1(y: 1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'this.E1(y: 1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(1, a)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(1, 0.1, 0.2)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 0.1, 0.2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, 0.1, 0.2)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0.1) (Syntax: '0.1') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0.2) (Syntax: '0.2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ParamsArrayArgumentInExpandedFormWithNoArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1)/*</bind>*/; } void M2(int x, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2(System.Int32 x, params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(1)') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndParamsArrayArgumentInExpandedFormWithNoArgument() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2()/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2()') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2()') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2()') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndNamedParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(array: a)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: a)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(array: a)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueAndNamedParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(array: 1)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(array: 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(array: 1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(array: 1)') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentAndNamedParamsArrayArgumentInNormalForm() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(1, array: a)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, array: a)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PositionalArgumentAndNamedParamsArrayArgumentInExpandedForm() { string source = @" class P { void M1() { /*<bind>*/M2(1, array: 1)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, array: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, array: 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(1, array: 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1, array: 1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, array: 1)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentAndNamedParamsArrayArgumentInNormalFormOutOfParameterOrder() { string source = @" class P { void M1() { var a = new[] { 0.0 }; /*<bind>*/M2(array: a, x: 1);/*</bind>*/ } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(array: a, x: 1);') Expression: IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: a, x: 1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: array) (OperationKind.Argument, Type: null) (Syntax: 'array: a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Double[]) (Syntax: 'a') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NamedArgumentAndNamedParamsArrayArgumentInExpandedFormOutOfParameterOrder() { string source = @" class P { void M1() { /*<bind>*/M2(array: 1, x: 10)/*</bind>*/; } void M2(int x = 0, params double[] array) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.Int32 x = 0], params System.Double[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(array: 1, x: 10)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(2): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Double[], IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(array: 1, x: 10)') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x: 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInMethod() { string source = @" using System.Runtime.CompilerServices; class P { void M1() { /*<bind>*/M2()/*</bind>*/; } void M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""M1"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInProperty() { string source = @" using System.Runtime.CompilerServices; class P { bool M1 => /*<bind>*/M2()/*</bind>*/; bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation ( System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""M1"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInFieldInitializer() { string source = @" using System.Runtime.CompilerServices; class P { bool field = /*<bind>*/M2()/*</bind>*/; static bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation (System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""field"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CallerInfoAttributesInvokedInEventMethods() { string source = @" using System; using System.Runtime.CompilerServices; class P { public event EventHandler MyEvent { add { /*<bind>*/M2()/*</bind>*/; } remove { M2(); } } static bool M2( [CallerMemberName] string memberName = null, [CallerFilePath] string sourceFilePath = null, [CallerLineNumber] int sourceLineNumber = 0) { return true; } } "; string expectedOperationTree = @" IInvocationOperation (System.Boolean P.M2([System.String memberName = null], [System.String sourceFilePath = null], [System.Int32 sourceLineNumber = 0])) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'M2()') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: memberName) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""MyEvent"", IsImplicit) (Syntax: 'M2()') 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: sourceFilePath) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""file.cs"", IsImplicit) (Syntax: 'M2()') 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: sourceLineNumber) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>((source, "file.cs"), expectedOperationTree, TargetFramework.Mscorlib46, expectedDiagnostics); } [Fact] public void DefaultArgument_CallerInfo_BadParameterType() { var source0 = @" using System.Runtime.CompilerServices; public class C0 { public static void M0([CallerLineNumber] string s = ""hello"") { } // 1 } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; // 2 } } "; var expectedOperationTree = @" IInvocationOperation (void C0.M0([System.String s = ""hello""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsInvalid, IsImplicit) (Syntax: 'C0.M0()') 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 expectedDiagnostics0And1 = new[] { // (6,28): error CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type 'int' to type 'string' // public static void M0([CallerLineNumber] string s = "hello") { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForCallerLineNumberParam, "CallerLineNumber").WithArguments("int", "string").WithLocation(6, 28), // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' // /*<bind>*/C0.M0()/*</bind>*/; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19), }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(CreateCompilation(new[] { source1, source0 }), expectedOperationTree, expectedDiagnostics0And1); var expectedDiagnostics1 = new[] { // (6,19): error CS0029: Cannot implicitly convert type 'int' to 'string' // /*<bind>*/C0.M0()/*</bind>*/; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "C0.M0()").WithArguments("int", "string").WithLocation(6, 19) }; var lib0 = CreateCompilation(source0).ToMetadataReference(); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(CreateCompilation(new[] { source1 }, references: new[] { lib0 }), expectedOperationTree, expectedDiagnostics1); CreateCompilation(new[] { source1 }, references: new[] { lib0 }).VerifyEmitDiagnostics(expectedDiagnostics1); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ExtraArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1, 2)/*</bind>*/; } void M2(int x = 0) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1, 2)') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'M2' takes 2 arguments // /*<bind>*/M2(1, 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "M2").WithArguments("M2", "2").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestOmittedArgument() { string source = @" class P { void M1() { /*<bind>*/M2(1,)/*</bind>*/; } void M2(int y, int x = 0) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1,)') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,24): error CS1525: Invalid expression term ')' // /*<bind>*/M2(1,)/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void WrongArgumentType() { string source = @" class P { void M1() { /*<bind>*/M2(1)/*</bind>*/; } void M2(string x ) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS1503: Argument 1: cannot convert from 'int' to 'string' // /*<bind>*/M2(1)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(6, 22) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VarArgsCall() { string source = @" using System; public class P { void M() { /*<bind>*/Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5))/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation (void System.Console.Write(System.String format, System.Object arg0, System.Object arg1, System.Object arg2, System.Object arg3, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... arglist(5))') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: format) (OperationKind.Argument, Type: null) (Syntax: '""{0} {1} {2} {3} {4}""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""{0} {1} {2} {3} {4}"") (Syntax: '""{0} {1} {2} {3} {4}""') 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.Explicit, Matching Parameter: arg0) (OperationKind.Argument, Type: null) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') 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.Explicit, Matching Parameter: arg3) (OperationKind.Argument, Type: null) (Syntax: '4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') 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.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(5)') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(5)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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<InvocationExpressionSyntax>(source, expectedOperationTree, TargetFramework.Mscorlib45, expectedDiagnostics); } /// <summary> /// See <see cref="InvalidConversionForDefaultArgument_InIL" /> for a similar scenario for involving a bad constant value from metadata. /// </summary> [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_InSource() { var source0 = @" public class C0 { public static void M0(int x = ""string"") { } // 1 } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Parameter default values in source produce ConstantValue.Bad when they fail to convert to the parameter type, // and when we use that to create a default argument, we just fall back to default(ParameterType). // This has the effect of reducing cascading diagnostics when a parameter default value is bad in source. // On the other hand, if `void M2(int)` came from metadata (i.e. hand-written malformed IL), we would produce a string ConstantValue for it, // and the operation tree would contain a bad conversion to int with an operand of type string. We also produce a compilation error for the bad conversion. var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.Int32 x = default(System.Int32)])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'C0.M0()') 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 expectedDiagnostics0 = new DiagnosticDescription[] { // (4,31): error CS1750: A value of type 'string' cannot be used as a default parameter because there are no standard conversions to type 'int' // public static void M0(int x = "string") { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("string", "int").WithLocation(4, 31) }; var comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, expectedDiagnostics0); comp.VerifyEmitDiagnostics(expectedDiagnostics0); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(expectedDiagnostics0); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ValidConversionForDefaultArgument_DateTime() { var source0 = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DateTimeConstant(634953547672667479L)] DateTime x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.DateTime x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') ILiteralOperation (OperationKind.Literal, Type: System.DateTime, Constant: 02/01/2013 22:32:47, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_DateTime() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DateTimeConstant(634953547672667479L)] string x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Note that DateTime constants which fail to convert to the parameter type are silently replaced with default(T). var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.String x])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ValidConversionForDefaultArgument_Decimal() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] decimal x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.Decimal x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 50, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidConversionForDefaultArgument_Decimal() { var source0 = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class C0 { public static void M0([Optional, DecimalConstant(0, 0, 0, 0, 50)] string x) { } } "; var source1 = @" public class C1 { public static void M1() { /*<bind>*/C0.M0()/*</bind>*/; } } "; // Note that decimal constants which fail to convert to the parameter type are silently replaced with default(T). var expectedOperationTree0And1 = @" IInvocationOperation (void C0.M0([System.String x = 50])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C0.M0()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'C0.M0()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.String, Constant: null, IsImplicit) (Syntax: 'C0.M0()') 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 comp = CreateCompilation(new[] { source1, source0 }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp, expectedOperationTree0And1, DiagnosticDescription.None); comp.VerifyEmitDiagnostics(); var comp0 = CreateCompilation(source0); comp0.VerifyEmitDiagnostics(); var comp1 = CreateCompilation(source1, references: new[] { comp0.ToMetadataReference() }); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(comp1, expectedOperationTree0And1, DiagnosticDescription.None); comp1.VerifyEmitDiagnostics(DiagnosticDescription.None); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ReadingFromIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } set { _number = value; } } void M1() { var x = /*<bind>*/this[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultArgumentForIndexerGetter() { string source = @" class P { private int _number = 0; public int this[int i = 1, int j = 2] { get { return _number; } set { _number = i + j; } } void M1() { var x = /*<bind>*/this[j:10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 1], [System.Int32 j = 2]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[j:10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: j) (OperationKind.Argument, Type: null) (Syntax: 'j:10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[j:10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'this[j:10]') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ReadingFromWriteOnlyIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { set { _number = value; } } void M1() { var x = /*<bind>*/this[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') 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[] { // file.cs(12,27): error CS0154: The property or indexer 'P.this[int]' cannot be used in this context because it lacks the get accessor // var x = /*<bind>*/this[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[10]").WithArguments("P.this[int]").WithLocation(12, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReadOnlyIndexer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } } void M1() { /*<bind>*/this[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index] { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'this[10]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') 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[] { // file.cs(12,19): error CS0200: Property or indexer 'P.this[int]' cannot be assigned to -- it is read only // /*<bind>*/this[10]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[10]").WithArguments("P.this[int]").WithLocation(12, 19) }; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OverridingIndexerWithDefaultArgument() { string source = @" class Base { public virtual int this[int x = 0, int y = 1] { set { } get { System.Console.Write(y); return 0; } } } class Derived : Base { public override int this[int x = 8, int y = 9] { set { } } } internal class P { static void Main() { var d = new Derived(); var x = /*<bind>*/d[0]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 Derived.this[[System.Int32 x = 8], [System.Int32 y = 9]] { set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'd[0]') Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: Derived) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'd[0]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'd[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; string expectedOutput = @"1"; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { source }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OmittedParamArrayArgumentInIndexerAccess() { string source = @" class P { public int this[int x, params int[] y] { set { } get { return 0; } } public void M() { /*<bind>*/this[0]/*</bind>*/ = 0; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 x, params System.Int32[] y] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'this[0]') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[0]') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReturnsByRefIndexer() { string source = @" class P { ref int this[int x] { get => throw null; } public void M() { /*<bind>*/this[0]/*</bind>*/ = 0; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: ref System.Int32 P.this[System.Int32 x] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void AssigningToIndexer_UsingDefaultArgumentFromSetter() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); /*<bind>*/p[10]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 4 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ReadFromIndexer_UsingDefaultArgumentFromGetter() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); var x = /*<bind>*/p[10]/*</bind>*/; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 2 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void IndexerAccess_LHSOfCompoundAssignment() { var il = @" .class public auto ansi beforefieldinit P extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .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 specialname instance int32 get_Item([opt] int32 i, [opt] int32 j) cil managed { .param [1] = int32(0x00000001) .param [2] = int32(0x00000002) // Code size 35 (0x23) .maxstack 3 .locals init ([0] int32 V_0) IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ldc.i4.0 IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } // end of method P::get_Item .method public hidebysig specialname instance void set_Item([opt] int32 i, [opt] int32 j, int32 'value') cil managed { .param [1] = int32(0x00000003) .param [2] = int32(0x00000004) // Code size 30 (0x1e) .maxstack 8 IL_0000: nop IL_0001: ldstr ""{0} {1}"" IL_0006: ldarg.1 IL_0007: box [mscorlib]System.Int32 IL_000c: ldarg.2 IL_000d: box [mscorlib]System.Int32 IL_0012: call string [mscorlib]System.String::Format(string, object, object) IL_0017: call void [mscorlib]System.Console::WriteLine(string) IL_001c: nop IL_001d: ret } // end of method P::set_Item .property instance int32 Item(int32, int32) { .get instance int32 P::get_Item(int32, int32) .set instance void P::set_Item(int32, int32, int32) } // end of property P::Item } // end of class P "; var csharp = @" class C { public static void Main(string[] args) { P p = new P(); /*<bind>*/p[10]/*</bind>*/ += 99; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[[System.Int32 i = 3], [System.Int32 j = 4]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'p[10]') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P) (Syntax: 'p') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') 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: j) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'p[10]') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'p[10]') 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; var expectedOutput = @"10 2 10 2 "; var ilReference = VerifyOperationTreeAndDiagnosticsForTestWithIL<ElementAccessExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics, additionalOperationTreeVerifier: IndexerAccessArgumentVerifier.Verify); CompileAndVerify(new[] { csharp }, new[] { ilReference }, expectedOutput: expectedOutput); } [CompilerTrait(CompilerFeature.IOperation)] [ClrOnlyFact(ClrOnlyReason.Ilasm)] 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 void M1([opt] int32 s) cil managed { .param [1] = ""abc"" // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method P::M1 } // end of class P "; var csharp = @" class C { public void M2() { P p = new P(); /*<bind>*/p.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation ( void P.M1([System.Int32 s = ""abc""])) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'p.M1()') Instance Receiver: ILocalReferenceOperation: p (OperationKind.LocalReference, Type: P, IsInvalid) (Syntax: 'p') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'p.M1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'p.M1()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"", IsInvalid, IsImplicit) (Syntax: 'p.M1()') 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[] { // file.cs(7,20): error CS0029: Cannot implicitly convert type 'string' to 'int' // /*<bind>*/p.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 20) }; VerifyOperationTreeAndDiagnosticsForTestWithIL<InvocationExpressionSyntax>(csharp, il, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_Call() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(bool? x = true) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Boolean[missing]? x = true])) (OperationKind.Invocation, Type: System.Void[missing], IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: 'M2()') 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[] { // (4,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(4, 12), // (9,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 20), // (9,20): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 20), // (9,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(9, 12), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (9,30): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "true").WithArguments("System.Boolean").WithLocation(9, 30), // (6,19): error CS0518: Predefined type 'System.Object' is not defined or imported // /*<bind>*/M2()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "M2").WithArguments("System.Object").WithLocation(6, 19), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P()/*</bind>*/; } P(bool? x = true) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor([System.Boolean[missing]? x = true])) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'new P()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'new P()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Boolean[missing], Constant: True, IsInvalid, IsImplicit) (Syntax: '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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,12): error CS0518: Predefined type 'System.Object' is not defined or imported // static P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(4, 12), // (9,7): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 7), // (9,7): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 7), // (9,5): error CS0518: Predefined type 'System.Void' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"P(bool? x = true) { }").WithArguments("System.Void").WithLocation(9, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (9,17): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = true) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "true").WithArguments("System.Boolean").WithLocation(9, 17), // (6,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(6, 30), // (9,5): error CS1729: 'object' does not contain a constructor that takes 0 arguments // P(bool? x = true) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(9, 5) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_Indexer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = 5] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = 5]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'this[0]') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[0]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 5, IsInvalid, IsImplicit) (Syntax: 'this[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[] { // (5,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 13), // (6,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 12), // (6,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 21), // (6,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(6, 28), // (6,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(6, 28), // (9,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(9, 9), // (12,5): error CS0518: Predefined type 'System.Void' is not defined or imported // void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(12, 5), // (3,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(3, 7), // (6,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 5] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "5").WithArguments("System.Int32").WithLocation(6, 37), // (5,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(5, 27), // (14,24): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(14, 24), // (14,40): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "9").WithArguments("System.Int32").WithLocation(14, 40), // (3,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(3, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_Call() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(bool? x = null) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Boolean[missing]? x = null])) (OperationKind.Invocation, Type: System.Void[missing], IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: 'M2()') 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[] { // (4,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(4, 12), // (9,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 20), // (9,20): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 20), // (9,12): error CS0518: Predefined type 'System.Void' is not defined or imported // static void M2(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(9, 12), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (6,19): error CS0518: Predefined type 'System.Object' is not defined or imported // /*<bind>*/M2()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "M2").WithArguments("System.Object").WithLocation(6, 19), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P()/*</bind>*/; } P(bool? x = null) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor([System.Boolean[missing]? x = null])) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P()') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'new P()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Boolean[missing]?, IsInvalid, IsImplicit) (Syntax: '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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,12): error CS0518: Predefined type 'System.Object' is not defined or imported // static P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(4, 12), // (9,7): error CS0518: Predefined type 'System.Boolean' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(9, 7), // (9,7): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool?").WithArguments("System.Nullable`1").WithLocation(9, 7), // (9,5): error CS0518: Predefined type 'System.Void' is not defined or imported // P(bool? x = null) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"P(bool? x = null) { }").WithArguments("System.Void").WithLocation(9, 5), // (6,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P()/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(6, 30), // (9,5): error CS1729: 'object' does not contain a constructor that takes 0 arguments // P(bool? x = null) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(9, 5) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_Indexer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = null] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'this[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: 'this[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[] { // (16,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(16, 1), // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Void' is not defined or imported // void M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,24): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 24), // (13,40): error CS0518: Predefined type 'System.Int32' is not defined or imported // /*<bind>*/this[0]/*</bind>*/ = 9; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "9").WithArguments("System.Int32").WithLocation(13, 40), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(20330, "https://github.com/dotnet/roslyn/issues/20330")] public void DefaultValueWithParameterErrorType_Call() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, S s = 0) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [S s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,27): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, S s = 0) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 27), // file.cs(9,29): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // static void M2(int x, S s = 0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 29) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<InvocationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_ObjectCreation() { string source = @" class P { static P M1() { return /*<bind>*/new P(1)/*</bind>*/; } P(int x, S s = 0) { } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor(System.Int32 x, [S s = null])) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(1)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'new P(1)') 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) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,14): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // P(int x, S s = 0) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 14), // file.cs(9,16): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // P(int x, S s = 0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(9, 16) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ObjectCreationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_Indexer() { string source = @" class P { private int _number = 0; public int this[int index, S s = 0] { get { return _number; } set { _number = value; } } void M1() { /*<bind>*/this[0]/*</bind>*/ = 9; } } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[System.Int32 index, [S s = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: 'this[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[] { // file.cs(5,32): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // public int this[int index, S s = 0] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(5, 32), // file.cs(5,34): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public int this[int index, S s = 0] Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 34) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ElementAccessExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18722, "https://github.com/dotnet/roslyn/issues/18722")] public void DefaultValueForGenericWithUndefinedTypeArgument() { // TODO: https://github.com/dotnet/roslyn/issues/18722 // This should be treated as invalid invocation. string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, G<S> s = null) { } } class G<T> { } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [G<S> s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: G<S>, Constant: null, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,29): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, G<S> s = null) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18722, "https://github.com/dotnet/roslyn/issues/18722")] public void DefaultValueForNullableGenericWithUndefinedTypeArgument() { // TODO: https://github.com/dotnet/roslyn/issues/18722 // This should be treated as invalid invocation. string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x, G<S>? s = null) { } } struct G<T> { } "; string expectedOperationTree = @" IInvocationOperation (void P.M2(System.Int32 x, [G<S>? s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IDefaultValueOperation (OperationKind.DefaultValue, Type: G<S>?, IsImplicit) (Syntax: 'M2(1)') 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[] { // file.cs(9,29): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // static void M2(int x, G<S> s = null) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void GettingInOutConversionFromCSharpArgumentShouldThrowException() { string source = @" class P { static void M1() { /*<bind>*/M2(1)/*</bind>*/; } static void M2(int x) { } } "; var compilation = CreateCompilation(source); var (operation, syntaxNode) = GetOperationAndSyntaxForTest<InvocationExpressionSyntax>(compilation); var invocation = (IInvocationOperation)operation; var argument = invocation.Arguments[0]; // We are calling VB extension methods on IArgument in C# code, therefore exception is expected here. Assert.Throws<ArgumentException>(() => argument.GetInConversion()); Assert.Throws<ArgumentException>(() => argument.GetOutConversion()); } [Fact] public void DirectlyBindArgument_InvocationExpression() { string source = @" class P { static void M1() { M2(/*<bind>*/1/*</bind>*/); } static void M2(int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindRefArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; M2(/*<bind>*/ref i/*</bind>*/); } static void M2(ref int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'ref i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindInArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; ref int refI = ref i; M2(/*<bind>*/refI/*</bind>*/); } static void M2(in int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'refI') ILocalReferenceOperation: refI (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'refI') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindOutArgument_InvocationExpression() { string source = @" class P { static void M1() { int i = 0; M2(/*<bind>*/out i/*</bind>*/); } static void M2(out int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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[] { // CS0177: The out parameter 'i' must be assigned to before control leaves the current method // static void M2(out int i) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "M2").WithArguments("i").WithLocation(9, 17) }; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_InvocationExpression() { string source = @" class P { static void M1() { /*<bind>*/M2(1);/*</bind>*/ } static void M2(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1);') Expression: IInvocationOperation (void P.M2(params System.Int32[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'M2(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_InvocationExpression() { string source = @" class P { static void M1() { /*<bind>*/M2(0, 1);/*</bind>*/ } static void M2(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(0, 1);') Expression: IInvocationOperation (void P.M2(params System.Int32[] array)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(0, 1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(0, 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'M2(0, 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(0, 1)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(0, 1)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindNamedArgument1_InvocationExpression() { string source = @" class P { static void M1() { M2(/*<bind>*/j: 1/*</bind>*/, i: 1); } static void M2(int i, int j) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: j) (OperationKind.Argument, Type: null) (Syntax: 'j: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindNamedArgument2_InvocationExpression() { string source = @" class P { static void M1() { M2(j: 1, /*<bind>*/i: 1/*</bind>*/); } static void M2(int i, int j) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i: 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_ObjectCreation() { string source = @" class P { static void M1() { new P(/*<bind>*/1/*</bind>*/); } public P(int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindRefArgument_ObjectCreation() { string source = @" class P { static void M1() { int i = 0; new P(/*<bind>*/ref i/*</bind>*/); } public P(ref int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'ref i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindOutArgument_ObjectCreation() { string source = @" class P { static void M1() { int i = 0; new P(/*<bind>*/out i/*</bind>*/); } public P(out int i) { } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') 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[] { // CS0177: The out parameter 'i' must be assigned to before control leaves the current method // public P(out int i) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "P").WithArguments("i").WithLocation(9, 12) }; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_ObjectCreation() { string source = @" class P { static void M1() { /*<bind>*/new P(1);/*</bind>*/ } public P(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'new P(1);') Expression: IObjectCreationOperation (Constructor: P..ctor(params System.Int32[] array)) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(1)') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'new P(1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new P(1)') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'new P(1)') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_ObjectCreation() { string source = @" class P { static void M1() { /*<bind>*/new P(0, 1);/*</bind>*/ } public P(params int[] array) { } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'new P(0, 1);') Expression: IObjectCreationOperation (Constructor: P..ctor(params System.Int32[] array)) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P(0, 1)') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new P(0, 1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'new P(0, 1)') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new P(0, 1)') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'new P(0, 1)') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ExpressionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_Indexer() { string source = @" class P { void M1() { var v = this[/*<bind>*/1/*</bind>*/]; } public int this[int i] => 0; } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument1_Indexer() { string source = @" class P { void M1() { var v = /*<bind>*/this[1]/*</bind>*/; } public int this[params int[] array] => 0; } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[params System.Int32[] array] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[1]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[1]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'this[1]') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[1]') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindParamsArgument2_Indexer() { string source = @" class P { void M1() { var v = /*<bind>*/this[0, 1]/*</bind>*/; } public int this[params int[] array] => 0; } "; string expectedOperationTree = @" IPropertyReferenceOperation: System.Int32 P.this[params System.Int32[] array] { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'this[0, 1]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P) (Syntax: 'this') Arguments(1): IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: array) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'this[0, 1]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: 'this[0, 1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'this[0, 1]') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'this[0, 1]') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') 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<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_Attribute() { string source = @" [assembly: /*<bind>*/System.CLSCompliant(isCompliant: true)/*</bind>*/] "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: 'System.CLSC ... iant: true)') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AttributeSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument2_Attribute() { string source = @" [assembly: MyA(/*<bind>*/Prop = ""test""/*</bind>*/)] class MyA : System.Attribute { public string Prop {get;set;} } "; string expectedOperationTree = @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'Prop = ""test""') Left: IPropertyReferenceOperation: System.String MyA.Prop { get; set; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Prop') Instance Receiver: null Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""test"") (Syntax: '""test""') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AttributeArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void DirectlyBindArgument_NonTrailingNamedArgument() { string source = @" class P { void M1(int i, int i2) { M1(i: 0, /*<bind>*/2/*</bind>*/); } } "; string expectedOperationTree = @" IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArgumentSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NonNullDefaultValueForNullableParameterType() { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(int? x = 10) { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32? x = 10])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Theory] [InlineData("null")] [InlineData("default")] [InlineData("default(int?)")] public void NullDefaultValueForNullableParameterType(string defaultValue) { string source = @" class P { static void M1() { /*<bind>*/M2()/*</bind>*/; } static void M2(int? x = " + defaultValue + @") { } } "; string expectedOperationTree = @" IInvocationOperation (void P.M2([System.Int32? x = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2()') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32?, IsImplicit) (Syntax: 'M2()') 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<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void AssigningToReadOnlyIndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int index] { get { return _number; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '[0] = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: '[0]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(12,36): error CS0200: Property or indexer 'P.this[int]' cannot be assigned to -- it is read only // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "[0]").WithArguments("P.this[int]").WithLocation(12, 36) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void WrongSignatureIndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[string name] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '[0] = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: '[0]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(13,37): error CS1503: Argument 1: cannot convert from 'int' to 'string' // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "0").WithArguments("1", "int", "string").WithLocation(13, 37) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueNonNullForNullableParameterTypeWithMissingNullableReference_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = 0] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Children(1): IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[missing], IsInvalid) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = 0]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '[0]') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[0]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Object' is not defined or imported // P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (5,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = 0] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(5, 37), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(13, 30), // (13,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 37), // (13,42): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32").WithLocation(13, 42), // (13,30): error CS0518: Predefined type 'System.Void' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Void").WithLocation(13, 30), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueNullForNullableParameterTypeWithMissingNullableReference_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, int? y = null] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: P, IsInvalid) (Syntax: 'new P() { [0] = 1 }') Children(1): IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P, IsInvalid) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[missing], IsInvalid) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32[missing] P.this[System.Int32[missing] x, [System.Int32[missing]? y = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32[missing], IsInvalid) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 0, IsInvalid) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32[missing]?, IsInvalid, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32[missing], Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // (4,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 13), // (5,12): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 12), // (5,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 21), // (5,28): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(5, 28), // (5,28): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // public int this[int x, int? y = null] Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int?").WithArguments("System.Nullable`1").WithLocation(5, 28), // (8,9): error CS0518: Predefined type 'System.Void' is not defined or imported // set { _number = value; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set { _number = value; }").WithArguments("System.Void").WithLocation(8, 9), // (11,5): error CS0518: Predefined type 'System.Object' is not defined or imported // P M1() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(11, 5), // (2,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class P Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(2, 7), // (4,27): error CS0518: Predefined type 'System.Int32' is not defined or imported // private int _number = 0; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(4, 27), // (13,30): error CS0518: Predefined type 'System.Object' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Object").WithLocation(13, 30), // (13,37): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0").WithArguments("System.Int32").WithLocation(13, 37), // (13,42): error CS0518: Predefined type 'System.Int32' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32").WithLocation(13, 42), // (13,30): error CS0518: Predefined type 'System.Void' is not defined or imported // return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "P").WithArguments("System.Void").WithLocation(13, 30), // (2,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class P Diagnostic(ErrorCode.ERR_BadCtorArgCount, "P").WithArguments("object", "0").WithLocation(2, 7) }; var compilation = CreateEmptyCompilation(source, options: Test.Utilities.TestOptions.ReleaseDll); VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DefaultValueWithParameterErrorType_IndexerInObjectCreationInitializer() { string source = @" class P { private int _number = 0; public int this[int x, S s = 0] { get { return _number; } set { _number = value; } } P M1() { return /*<bind>*/new P() { [0] = 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: P..ctor()) (OperationKind.ObjectCreation, Type: P) (Syntax: 'new P() { [0] = 1 }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: P) (Syntax: '{ [0] = 1 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '[0] = 1') Left: IPropertyReferenceOperation: System.Int32 P.this[System.Int32 x, [S s = null]] { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '[0]') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: '[0]') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '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) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[0]') IDefaultValueOperation (OperationKind.DefaultValue, Type: S, IsImplicit) (Syntax: '[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) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,28): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // public int this[int x, S s = 0] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(5, 28), // file.cs(5,30): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public int this[int x, S s = 0] Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("int", "S").WithLocation(5, 30) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<ObjectCreationExpressionSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNullableDefaultArgument() { string source = @" public struct MyStruct { static void M1(MyStruct? s = default(MyStruct)) { } // 1 static void M2() { /*<bind>*/M1();/*</bind>*/ } } "; // Note that we fall back to a literal 'null' argument here because it's our general handling for bad default parameter values in source. string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1();') Expression: IInvocationOperation (void MyStruct.M1([MyStruct? s = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1()') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M1()') IDefaultValueOperation (OperationKind.DefaultValue, Type: MyStruct?, IsImplicit) (Syntax: 'M1()') 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[] { // (4,30): error CS1770: A value of type 'MyStruct' cannot be used as default parameter for nullable parameter 's' because 'MyStruct' is not a simple type // static void M1(MyStruct? s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "s").WithArguments("MyStruct", "s").WithLocation(4, 30) }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<StatementSyntax>(comp, expectedOperationTree); comp.VerifyEmitDiagnostics(expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NullableEnumDefaultArgument_NonZeroValue() { string source = @" #nullable enable public enum E { E1 = 1 } class C { void M0(E? e = E.E1) { } void M1() { /*<bind>*/M0();/*</bind>*/ } } "; string expectedOperationTree = @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M0();') Expression: IInvocationOperation ( void C.M0([E? e = 1])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M0()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M0') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: e) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M0()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: E?, IsImplicit) (Syntax: 'M0()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M0()') 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 comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); var operation = VerifyOperationTreeForTest<StatementSyntax>(comp, expectedOperationTree); var conversion = operation.Descendants().OfType<IConversionOperation>().Single(); // Note that IConversionOperation.IsImplicit refers to whether the code is implicitly generated by the compiler // while CommonConversion.IsImplicit refers to whether the conversion that was generated is an implicit conversion Assert.False(conversion.Conversion.IsImplicit); Assert.True(conversion.Conversion.IsNullable); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void UndefinedMethod() { string source = @" class P { static void M1() { /*<bind>*/M2(1, 2)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(1, 2)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0103: The name 'M2' does not exist in the current context // /*<bind>*/M2(1, 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "M2").WithArguments("M2").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } private class IndexerAccessArgumentVerifier : OperationWalker { private readonly Compilation _compilation; private IndexerAccessArgumentVerifier(Compilation compilation) { _compilation = compilation; } public static void Verify(IOperation operation, Compilation compilation, SyntaxNode syntaxNode) { new IndexerAccessArgumentVerifier(compilation).Visit(operation); } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { if (operation.HasErrors(_compilation) || operation.Arguments.Length == 0) { return; } // Check if the parameter symbol for argument is corresponding to indexer instead of accessor. var indexerSymbol = operation.Property; foreach (var argument in operation.Arguments) { if (!argument.HasErrors(_compilation)) { Assert.Same(indexerSymbol, argument.Parameter.ContainingSymbol); } } } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Core/Portable/Emit/EmitOptions.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.Security.Cryptography; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents compilation emit options. /// </summary> public sealed class EmitOptions : IEquatable<EmitOptions> { internal static readonly EmitOptions Default = PlatformInformation.IsWindows ? new EmitOptions() : new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb); /// <summary> /// True to emit an assembly excluding executable code such as method bodies. /// </summary> public bool EmitMetadataOnly { get; private set; } /// <summary> /// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors. /// </summary> public bool TolerateErrors { get; private set; } /// <summary> /// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded /// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on). /// If emitting a secondary output, this flag is required to be false. /// </summary> public bool IncludePrivateMembers { get; private set; } /// <summary> /// Type of instrumentation that should be added to the output binary. /// </summary> public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; } /// <summary> /// Subsystem version /// </summary> public SubsystemVersion SubsystemVersion { get; private set; } /// <summary> /// Specifies the size of sections in the output file. /// </summary> /// <remarks> /// Valid values are 0, 512, 1024, 2048, 4096 and 8192. /// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>. /// </remarks> public int FileAlignment { get; private set; } /// <summary> /// True to enable high entropy virtual address space for the output binary. /// </summary> public bool HighEntropyVirtualAddressSpace { get; private set; } /// <summary> /// Specifies the preferred base address at which to load the output DLL. /// </summary> public ulong BaseAddress { get; private set; } /// <summary> /// Debug information format. /// </summary> public DebugInformationFormat DebugInformationFormat { get; private set; } /// <summary> /// Assembly name override - file name and extension. If not specified the compilation name is used. /// </summary> /// <remarks> /// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary /// to override the name. /// /// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to /// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the /// name of the compilation, may not be visible at runtime and vice-versa. /// </remarks> public string? OutputNameOverride { get; private set; } /// <summary> /// The name of the PDB file to be embedded in the PE image, or null to use the default. /// </summary> /// <remarks> /// If not specified the file name of the source module with an extension changed to "pdb" is used. /// </remarks> public string? PdbFilePath { get; private set; } /// <summary> /// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File. /// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated. /// </summary> public HashAlgorithmName PdbChecksumAlgorithm { get; private set; } /// <summary> /// Runtime metadata version. /// </summary> public string? RuntimeMetadataVersion { get; private set; } /// <summary> /// The encoding used to parse source files that do not have a Byte Order Mark. If specified, /// is stored in the emitted PDB in order to allow recreating the original compilation. /// </summary> public Encoding? DefaultSourceFileEncoding { get; private set; } /// <summary> /// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files /// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded. /// </summary> public Encoding? FallbackSourceFileEncoding { get; private set; } // 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty) { } // 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm: null) { } // 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string? pdbFilePath, string? outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string? runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds, HashAlgorithmName? pdbChecksumAlgorithm) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm, defaultSourceFileEncoding: null, fallbackSourceFileEncoding: null) { } public EmitOptions( bool metadataOnly = false, DebugInformationFormat debugInformationFormat = 0, string? pdbFilePath = null, string? outputNameOverride = null, int fileAlignment = 0, ulong baseAddress = 0, bool highEntropyVirtualAddressSpace = false, SubsystemVersion subsystemVersion = default, string? runtimeMetadataVersion = null, bool tolerateErrors = false, bool includePrivateMembers = true, ImmutableArray<InstrumentationKind> instrumentationKinds = default, HashAlgorithmName? pdbChecksumAlgorithm = null, Encoding? defaultSourceFileEncoding = null, Encoding? fallbackSourceFileEncoding = null) { EmitMetadataOnly = metadataOnly; DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat; PdbFilePath = pdbFilePath; OutputNameOverride = outputNameOverride; FileAlignment = fileAlignment; BaseAddress = baseAddress; HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace; SubsystemVersion = subsystemVersion; RuntimeMetadataVersion = runtimeMetadataVersion; TolerateErrors = tolerateErrors; IncludePrivateMembers = includePrivateMembers; InstrumentationKinds = instrumentationKinds.NullToEmpty(); PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256; DefaultSourceFileEncoding = defaultSourceFileEncoding; FallbackSourceFileEncoding = fallbackSourceFileEncoding; } private EmitOptions(EmitOptions other) : this( other.EmitMetadataOnly, other.DebugInformationFormat, other.PdbFilePath, other.OutputNameOverride, other.FileAlignment, other.BaseAddress, other.HighEntropyVirtualAddressSpace, other.SubsystemVersion, other.RuntimeMetadataVersion, other.TolerateErrors, other.IncludePrivateMembers, other.InstrumentationKinds, other.PdbChecksumAlgorithm, other.DefaultSourceFileEncoding, other.FallbackSourceFileEncoding) { } public override bool Equals(object? obj) { return Equals(obj as EmitOptions); } public bool Equals(EmitOptions? other) { if (ReferenceEquals(other, null)) { return false; } return EmitMetadataOnly == other.EmitMetadataOnly && BaseAddress == other.BaseAddress && FileAlignment == other.FileAlignment && HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace && SubsystemVersion.Equals(other.SubsystemVersion) && DebugInformationFormat == other.DebugInformationFormat && PdbFilePath == other.PdbFilePath && PdbChecksumAlgorithm == other.PdbChecksumAlgorithm && OutputNameOverride == other.OutputNameOverride && RuntimeMetadataVersion == other.RuntimeMetadataVersion && TolerateErrors == other.TolerateErrors && IncludePrivateMembers == other.IncludePrivateMembers && InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) && DefaultSourceFileEncoding == other.DefaultSourceFileEncoding && FallbackSourceFileEncoding == other.FallbackSourceFileEncoding; } public override int GetHashCode() { return Hash.Combine(EmitMetadataOnly, Hash.Combine(BaseAddress.GetHashCode(), Hash.Combine(FileAlignment, Hash.Combine(HighEntropyVirtualAddressSpace, Hash.Combine(SubsystemVersion.GetHashCode(), Hash.Combine((int)DebugInformationFormat, Hash.Combine(PdbFilePath, Hash.Combine(PdbChecksumAlgorithm.GetHashCode(), Hash.Combine(OutputNameOverride, Hash.Combine(RuntimeMetadataVersion, Hash.Combine(TolerateErrors, Hash.Combine(IncludePrivateMembers, Hash.Combine(Hash.CombineValues(InstrumentationKinds), Hash.Combine(DefaultSourceFileEncoding, Hash.Combine(FallbackSourceFileEncoding, 0))))))))))))))); } public static bool operator ==(EmitOptions? left, EmitOptions? right) { return object.Equals(left, right); } public static bool operator !=(EmitOptions? left, EmitOptions? right) { return !object.Equals(left, right); } internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic) { if (!DebugInformationFormat.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat)); } foreach (var instrumentationKind in InstrumentationKinds) { if (!instrumentationKind.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind)); } } if (OutputNameOverride != null) { MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics); } if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment)) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment)); } if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString())); } if (PdbChecksumAlgorithm.Name != null) { try { IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose(); } catch { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString())); } } else if (isDeterministic) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, "")); } } internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage); internal static bool IsValidFileAlignment(int value) { switch (value) { case 512: case 1024: case 2048: case 4096: case 8192: return true; default: return false; } } public EmitOptions WithEmitMetadataOnly(bool value) { if (EmitMetadataOnly == value) { return this; } return new EmitOptions(this) { EmitMetadataOnly = value }; } public EmitOptions WithPdbFilePath(string path) { if (PdbFilePath == path) { return this; } return new EmitOptions(this) { PdbFilePath = path }; } public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name) { if (PdbChecksumAlgorithm == name) { return this; } return new EmitOptions(this) { PdbChecksumAlgorithm = name }; } public EmitOptions WithOutputNameOverride(string outputName) { if (OutputNameOverride == outputName) { return this; } return new EmitOptions(this) { OutputNameOverride = outputName }; } public EmitOptions WithDebugInformationFormat(DebugInformationFormat format) { if (DebugInformationFormat == format) { return this; } return new EmitOptions(this) { DebugInformationFormat = format }; } /// <summary> /// Sets the byte alignment for portable executable file sections. /// </summary> /// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param> public EmitOptions WithFileAlignment(int value) { if (FileAlignment == value) { return this; } return new EmitOptions(this) { FileAlignment = value }; } public EmitOptions WithBaseAddress(ulong value) { if (BaseAddress == value) { return this; } return new EmitOptions(this) { BaseAddress = value }; } public EmitOptions WithHighEntropyVirtualAddressSpace(bool value) { if (HighEntropyVirtualAddressSpace == value) { return this; } return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value }; } public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion) { if (subsystemVersion.Equals(SubsystemVersion)) { return this; } return new EmitOptions(this) { SubsystemVersion = subsystemVersion }; } public EmitOptions WithRuntimeMetadataVersion(string version) { if (RuntimeMetadataVersion == version) { return this; } return new EmitOptions(this) { RuntimeMetadataVersion = version }; } public EmitOptions WithTolerateErrors(bool value) { if (TolerateErrors == value) { return this; } return new EmitOptions(this) { TolerateErrors = value }; } public EmitOptions WithIncludePrivateMembers(bool value) { if (IncludePrivateMembers == value) { return this; } return new EmitOptions(this) { IncludePrivateMembers = value }; } public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds) { if (InstrumentationKinds == instrumentationKinds) { return this; } return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds }; } public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding) { if (DefaultSourceFileEncoding == defaultSourceFileEncoding) { return this; } return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding }; } public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding) { if (FallbackSourceFileEncoding == fallbackSourceFileEncoding) { return this; } return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding }; } } }
// Licensed to the .NET Foundation under one or more 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.Security.Cryptography; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents compilation emit options. /// </summary> public sealed class EmitOptions : IEquatable<EmitOptions> { internal static readonly EmitOptions Default = PlatformInformation.IsWindows ? new EmitOptions() : new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb); /// <summary> /// True to emit an assembly excluding executable code such as method bodies. /// </summary> public bool EmitMetadataOnly { get; private set; } /// <summary> /// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors. /// </summary> public bool TolerateErrors { get; private set; } /// <summary> /// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded /// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on). /// If emitting a secondary output, this flag is required to be false. /// </summary> public bool IncludePrivateMembers { get; private set; } /// <summary> /// Type of instrumentation that should be added to the output binary. /// </summary> public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; } /// <summary> /// Subsystem version /// </summary> public SubsystemVersion SubsystemVersion { get; private set; } /// <summary> /// Specifies the size of sections in the output file. /// </summary> /// <remarks> /// Valid values are 0, 512, 1024, 2048, 4096 and 8192. /// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>. /// </remarks> public int FileAlignment { get; private set; } /// <summary> /// True to enable high entropy virtual address space for the output binary. /// </summary> public bool HighEntropyVirtualAddressSpace { get; private set; } /// <summary> /// Specifies the preferred base address at which to load the output DLL. /// </summary> public ulong BaseAddress { get; private set; } /// <summary> /// Debug information format. /// </summary> public DebugInformationFormat DebugInformationFormat { get; private set; } /// <summary> /// Assembly name override - file name and extension. If not specified the compilation name is used. /// </summary> /// <remarks> /// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary /// to override the name. /// /// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to /// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the /// name of the compilation, may not be visible at runtime and vice-versa. /// </remarks> public string? OutputNameOverride { get; private set; } /// <summary> /// The name of the PDB file to be embedded in the PE image, or null to use the default. /// </summary> /// <remarks> /// If not specified the file name of the source module with an extension changed to "pdb" is used. /// </remarks> public string? PdbFilePath { get; private set; } /// <summary> /// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File. /// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated. /// </summary> public HashAlgorithmName PdbChecksumAlgorithm { get; private set; } /// <summary> /// Runtime metadata version. /// </summary> public string? RuntimeMetadataVersion { get; private set; } /// <summary> /// The encoding used to parse source files that do not have a Byte Order Mark. If specified, /// is stored in the emitted PDB in order to allow recreating the original compilation. /// </summary> public Encoding? DefaultSourceFileEncoding { get; private set; } /// <summary> /// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files /// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded. /// </summary> public Encoding? FallbackSourceFileEncoding { get; private set; } // 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty) { } // 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm: null) { } // 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string? pdbFilePath, string? outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string? runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds, HashAlgorithmName? pdbChecksumAlgorithm) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm, defaultSourceFileEncoding: null, fallbackSourceFileEncoding: null) { } public EmitOptions( bool metadataOnly = false, DebugInformationFormat debugInformationFormat = 0, string? pdbFilePath = null, string? outputNameOverride = null, int fileAlignment = 0, ulong baseAddress = 0, bool highEntropyVirtualAddressSpace = false, SubsystemVersion subsystemVersion = default, string? runtimeMetadataVersion = null, bool tolerateErrors = false, bool includePrivateMembers = true, ImmutableArray<InstrumentationKind> instrumentationKinds = default, HashAlgorithmName? pdbChecksumAlgorithm = null, Encoding? defaultSourceFileEncoding = null, Encoding? fallbackSourceFileEncoding = null) { EmitMetadataOnly = metadataOnly; DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat; PdbFilePath = pdbFilePath; OutputNameOverride = outputNameOverride; FileAlignment = fileAlignment; BaseAddress = baseAddress; HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace; SubsystemVersion = subsystemVersion; RuntimeMetadataVersion = runtimeMetadataVersion; TolerateErrors = tolerateErrors; IncludePrivateMembers = includePrivateMembers; InstrumentationKinds = instrumentationKinds.NullToEmpty(); PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256; DefaultSourceFileEncoding = defaultSourceFileEncoding; FallbackSourceFileEncoding = fallbackSourceFileEncoding; } private EmitOptions(EmitOptions other) : this( other.EmitMetadataOnly, other.DebugInformationFormat, other.PdbFilePath, other.OutputNameOverride, other.FileAlignment, other.BaseAddress, other.HighEntropyVirtualAddressSpace, other.SubsystemVersion, other.RuntimeMetadataVersion, other.TolerateErrors, other.IncludePrivateMembers, other.InstrumentationKinds, other.PdbChecksumAlgorithm, other.DefaultSourceFileEncoding, other.FallbackSourceFileEncoding) { } public override bool Equals(object? obj) { return Equals(obj as EmitOptions); } public bool Equals(EmitOptions? other) { if (ReferenceEquals(other, null)) { return false; } return EmitMetadataOnly == other.EmitMetadataOnly && BaseAddress == other.BaseAddress && FileAlignment == other.FileAlignment && HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace && SubsystemVersion.Equals(other.SubsystemVersion) && DebugInformationFormat == other.DebugInformationFormat && PdbFilePath == other.PdbFilePath && PdbChecksumAlgorithm == other.PdbChecksumAlgorithm && OutputNameOverride == other.OutputNameOverride && RuntimeMetadataVersion == other.RuntimeMetadataVersion && TolerateErrors == other.TolerateErrors && IncludePrivateMembers == other.IncludePrivateMembers && InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) && DefaultSourceFileEncoding == other.DefaultSourceFileEncoding && FallbackSourceFileEncoding == other.FallbackSourceFileEncoding; } public override int GetHashCode() { return Hash.Combine(EmitMetadataOnly, Hash.Combine(BaseAddress.GetHashCode(), Hash.Combine(FileAlignment, Hash.Combine(HighEntropyVirtualAddressSpace, Hash.Combine(SubsystemVersion.GetHashCode(), Hash.Combine((int)DebugInformationFormat, Hash.Combine(PdbFilePath, Hash.Combine(PdbChecksumAlgorithm.GetHashCode(), Hash.Combine(OutputNameOverride, Hash.Combine(RuntimeMetadataVersion, Hash.Combine(TolerateErrors, Hash.Combine(IncludePrivateMembers, Hash.Combine(Hash.CombineValues(InstrumentationKinds), Hash.Combine(DefaultSourceFileEncoding, Hash.Combine(FallbackSourceFileEncoding, 0))))))))))))))); } public static bool operator ==(EmitOptions? left, EmitOptions? right) { return object.Equals(left, right); } public static bool operator !=(EmitOptions? left, EmitOptions? right) { return !object.Equals(left, right); } internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic) { if (!DebugInformationFormat.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat)); } foreach (var instrumentationKind in InstrumentationKinds) { if (!instrumentationKind.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind)); } } if (OutputNameOverride != null) { MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics); } if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment)) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment)); } if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString())); } if (PdbChecksumAlgorithm.Name != null) { try { IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose(); } catch { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString())); } } else if (isDeterministic) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, "")); } } internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage); internal static bool IsValidFileAlignment(int value) { switch (value) { case 512: case 1024: case 2048: case 4096: case 8192: return true; default: return false; } } public EmitOptions WithEmitMetadataOnly(bool value) { if (EmitMetadataOnly == value) { return this; } return new EmitOptions(this) { EmitMetadataOnly = value }; } public EmitOptions WithPdbFilePath(string path) { if (PdbFilePath == path) { return this; } return new EmitOptions(this) { PdbFilePath = path }; } public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name) { if (PdbChecksumAlgorithm == name) { return this; } return new EmitOptions(this) { PdbChecksumAlgorithm = name }; } public EmitOptions WithOutputNameOverride(string outputName) { if (OutputNameOverride == outputName) { return this; } return new EmitOptions(this) { OutputNameOverride = outputName }; } public EmitOptions WithDebugInformationFormat(DebugInformationFormat format) { if (DebugInformationFormat == format) { return this; } return new EmitOptions(this) { DebugInformationFormat = format }; } /// <summary> /// Sets the byte alignment for portable executable file sections. /// </summary> /// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param> public EmitOptions WithFileAlignment(int value) { if (FileAlignment == value) { return this; } return new EmitOptions(this) { FileAlignment = value }; } public EmitOptions WithBaseAddress(ulong value) { if (BaseAddress == value) { return this; } return new EmitOptions(this) { BaseAddress = value }; } public EmitOptions WithHighEntropyVirtualAddressSpace(bool value) { if (HighEntropyVirtualAddressSpace == value) { return this; } return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value }; } public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion) { if (subsystemVersion.Equals(SubsystemVersion)) { return this; } return new EmitOptions(this) { SubsystemVersion = subsystemVersion }; } public EmitOptions WithRuntimeMetadataVersion(string version) { if (RuntimeMetadataVersion == version) { return this; } return new EmitOptions(this) { RuntimeMetadataVersion = version }; } public EmitOptions WithTolerateErrors(bool value) { if (TolerateErrors == value) { return this; } return new EmitOptions(this) { TolerateErrors = value }; } public EmitOptions WithIncludePrivateMembers(bool value) { if (IncludePrivateMembers == value) { return this; } return new EmitOptions(this) { IncludePrivateMembers = value }; } public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds) { if (InstrumentationKinds == instrumentationKinds) { return this; } return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds }; } public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding) { if (DefaultSourceFileEncoding == defaultSourceFileEncoding) { return this; } return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding }; } public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding) { if (FallbackSourceFileEncoding == fallbackSourceFileEncoding) { return this; } return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding }; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/ChangeSignature/CallSiteKind.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.ChangeSignature { internal enum CallSiteKind { /// <summary> /// Use an explicit value to populate call sites, without forcing /// the addition of a named argument. /// </summary> Value, /// <summary> /// Use an explicit value to populate call sites, and convert /// arguments to named arguments even if not required. Often /// useful for literal callsite values like "true" or "null". /// </summary> ValueWithName, /// <summary> /// Indicates whether a "TODO" should be introduced at callsites /// to cause errors that the user can then go visit and fix up. /// </summary> Todo, /// <summary> /// When an optional parameter is added, passing an argument for /// it is not required. This indicates that the corresponding argument /// should be omitted. This often results in subsequent arguments needing /// to become named arguments /// </summary> Omitted, /// <summary> /// Populate each call site with an available variable of a matching types. /// If no matching variable is found, this falls back to the /// <see cref="Todo"/> behavior. /// </summary> Inferred } }
// Licensed to the .NET Foundation under one or more 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.ChangeSignature { internal enum CallSiteKind { /// <summary> /// Use an explicit value to populate call sites, without forcing /// the addition of a named argument. /// </summary> Value, /// <summary> /// Use an explicit value to populate call sites, and convert /// arguments to named arguments even if not required. Often /// useful for literal callsite values like "true" or "null". /// </summary> ValueWithName, /// <summary> /// Indicates whether a "TODO" should be introduced at callsites /// to cause errors that the user can then go visit and fix up. /// </summary> Todo, /// <summary> /// When an optional parameter is added, passing an argument for /// it is not required. This indicates that the corresponding argument /// should be omitted. This often results in subsequent arguments needing /// to become named arguments /// </summary> Omitted, /// <summary> /// Populate each call site with an available variable of a matching types. /// If no matching variable is found, this falls back to the /// <see cref="Todo"/> behavior. /// </summary> Inferred } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpArgumentProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpArgumentProvider : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpArgumentProvider(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpArgumentProvider)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true); } [WpfFact] public void SimpleTabTabCompletion() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteObjectEquals() { SetUpEditor(@" public class Test { public void Method() { $$ } } "); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteNewObject() { SetUpEditor(@" public class Test { public void Method() { var value = $$ } } "); VisualStudio.Editor.SendKeys("new obje"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("var value = new object($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object()$$", assertCaretPosition: true); } [WpfFact] public void TabTabBeforeSemicolon() { SetUpEditor(@" public class Test { private object f; public void Method() { $$; } } "); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$;", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$);", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$;", assertCaretPosition: true); } [WpfFact] public void TabTabCompletionWithArguments() { SetUpEditor(@" using System; public class Test { private int f; public void Method(IFormatProvider provider) {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("\"format\""); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); } [WpfFact] public void FullCycle() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Test"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); } [WpfFact] public void ImplicitArgumentSwitching() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Tes"); // Trigger the session and type '0' without waiting for the session to finish initializing VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0'); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); } /// <summary> /// Argument completion with no arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); } /// <summary> /// Argument completion with one or more arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void SmartBreakLineWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { f.ToString(); $$ } } ", assertCaretPosition: true); } [WpfFact] public void SmartBreakLineWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { object.Equals(null); $$ } } ", assertCaretPosition: true); } [WpfTheory] [InlineData("\"<\"", Skip = "https://github.com/dotnet/roslyn/issues/29669")] [InlineData("\">\"")] // testing things that might break XML [InlineData("\"&\"")] [InlineData("\" \"")] [InlineData("\"$placeholder$\"")] // ensuring our snippets aren't substituted in ways we don't expect [InlineData("\"$end$\"")] public void EnsureParameterContentPreserved(string parameterText) { SetUpEditor(@" public class Test { public void Method() {$$ } public void M(string s, int i) { } public void M(string s, int i, int i2) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("M"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("M$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("M(null, 0)"); VisualStudio.Editor.SendKeys(parameterText); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0)"); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0, 0)"); } [WpfFact] [WorkItem(54038, "https://github.com/dotnet/roslyn/issues/54038")] public void InsertPreprocessorSnippet() { SetUpEditor(@" using System; public class TestClass { $$ } "); VisualStudio.Editor.SendKeys("#i"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if true$$", assertCaretPosition: true); var expected = @" using System; public class TestClass { #if true #endif } "; AssertEx.EqualOrDiff(expected, VisualStudio.Editor.GetText()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpArgumentProvider : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpArgumentProvider(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpArgumentProvider)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true); } [WpfFact] public void SimpleTabTabCompletion() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteObjectEquals() { SetUpEditor(@" public class Test { public void Method() { $$ } } "); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void TabTabCompleteNewObject() { SetUpEditor(@" public class Test { public void Method() { var value = $$ } } "); VisualStudio.Editor.SendKeys("new obje"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("var value = new object($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("var value = new object()$$", assertCaretPosition: true); } [WpfFact] public void TabTabBeforeSemicolon() { SetUpEditor(@" public class Test { private object f; public void Method() { $$; } } "); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$;", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$);", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$;", assertCaretPosition: true); } [WpfFact] public void TabTabCompletionWithArguments() { SetUpEditor(@" using System; public class Test { private int f; public void Method(IFormatProvider provider) {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(null$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("\"format\""); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true); } [WpfFact] public void FullCycle() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Test"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); } [WpfFact] public void ImplicitArgumentSwitching() { SetUpEditor(@" using System; public class TestClass { public void Method() {$$ } void Test() { } void Test(int x) { } void Test(int x, int y) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("Tes"); // Trigger the session and type '0' without waiting for the session to finish initializing VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0'); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Up); VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true); } /// <summary> /// Argument completion with no arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); } /// <summary> /// Argument completion with one or more arguments. /// </summary> [WpfFact] public void SemicolonWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null)$$", assertCaretPosition: true); } [WpfFact] public void SmartBreakLineWithTabTabCompletion1() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("f.ToSt"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { f.ToString(); $$ } } ", assertCaretPosition: true); } [WpfFact] public void SmartBreakLineWithTabTabCompletion2() { SetUpEditor(@" public class Test { private object f; public void Method() {$$ } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("object.Equ"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("object.Equals$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("object.Equals(null$$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter)); VisualStudio.Editor.Verify.TextContains(@" public class Test { private object f; public void Method() { object.Equals(null); $$ } } ", assertCaretPosition: true); } [WpfTheory] [InlineData("\"<\"", Skip = "https://github.com/dotnet/roslyn/issues/29669")] [InlineData("\">\"")] // testing things that might break XML [InlineData("\"&\"")] [InlineData("\" \"")] [InlineData("\"$placeholder$\"")] // ensuring our snippets aren't substituted in ways we don't expect [InlineData("\"$end$\"")] public void EnsureParameterContentPreserved(string parameterText) { SetUpEditor(@" public class Test { public void Method() {$$ } public void M(string s, int i) { } public void M(string s, int i, int i2) { } } "); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.SendKeys("M"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("M$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp); VisualStudio.Editor.Verify.CurrentLineText("M(null, 0)"); VisualStudio.Editor.SendKeys(parameterText); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0)"); VisualStudio.Editor.SendKeys(VirtualKey.Down); VisualStudio.Editor.Verify.CurrentLineText("M(" + parameterText + ", 0, 0)"); } [WpfFact] [WorkItem(54038, "https://github.com/dotnet/roslyn/issues/54038")] public void InsertPreprocessorSnippet() { SetUpEditor(@" using System; public class TestClass { $$ } "); VisualStudio.Editor.SendKeys("#i"); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if$$", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("#if true$$", assertCaretPosition: true); var expected = @" using System; public class TestClass { #if true #endif } "; AssertEx.EqualOrDiff(expected, VisualStudio.Editor.GetText()); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Core/Portable/CommandLine/TouchedFileLogger.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 Roslyn.Utilities; using System; using System.IO; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging all the paths which are "touched" (used) in any way /// in the process of compilation. /// </summary> internal class TouchedFileLogger { private ConcurrentSet<string> _readFiles; private ConcurrentSet<string> _writtenFiles; public TouchedFileLogger() { _readFiles = new ConcurrentSet<string>(); _writtenFiles = new ConcurrentSet<string>(); } /// <summary> /// Adds a fully-qualified path to the Logger for a read file. /// Semantics are undefined after a call to <see cref="WriteReadPaths(TextWriter)" />. /// </summary> public void AddRead(string path) { if (path == null) throw new ArgumentNullException(path); _readFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a written file. /// Semantics are undefined after a call to <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddWritten(string path) { if (path == null) throw new ArgumentNullException(path); _writtenFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a read and written /// file. Semantics are undefined after a call to /// <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddReadWritten(string path) { AddRead(path); AddWritten(path); } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteReadPaths(TextWriter s) { var temp = new string[_readFiles.Count]; int i = 0; var readFiles = Interlocked.Exchange( ref _readFiles, null!); foreach (var path in readFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteWrittenPaths(TextWriter s) { var temp = new string[_writtenFiles.Count]; int i = 0; var writtenFiles = Interlocked.Exchange( ref _writtenFiles, null!); foreach (var path in writtenFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.IO; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging all the paths which are "touched" (used) in any way /// in the process of compilation. /// </summary> internal class TouchedFileLogger { private ConcurrentSet<string> _readFiles; private ConcurrentSet<string> _writtenFiles; public TouchedFileLogger() { _readFiles = new ConcurrentSet<string>(); _writtenFiles = new ConcurrentSet<string>(); } /// <summary> /// Adds a fully-qualified path to the Logger for a read file. /// Semantics are undefined after a call to <see cref="WriteReadPaths(TextWriter)" />. /// </summary> public void AddRead(string path) { if (path == null) throw new ArgumentNullException(path); _readFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a written file. /// Semantics are undefined after a call to <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddWritten(string path) { if (path == null) throw new ArgumentNullException(path); _writtenFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a read and written /// file. Semantics are undefined after a call to /// <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddReadWritten(string path) { AddRead(path); AddWritten(path); } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteReadPaths(TextWriter s) { var temp = new string[_readFiles.Count]; int i = 0; var readFiles = Interlocked.Exchange( ref _readFiles, null!); foreach (var path in readFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteWrittenPaths(TextWriter s) { var temp = new string[_writtenFiles.Count]; int i = 0; var writtenFiles = Interlocked.Exchange( ref _writtenFiles, null!); foreach (var path in writtenFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateClonedParameterSymbolForBeginAndEndInvoke.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceDelegateClonedParameterSymbolForBeginAndEndInvoke : SourceClonedParameterSymbol { internal SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(SourceParameterSymbol originalParam, SourceDelegateMethodSymbol newOwner, int newOrdinal) : base(originalParam, newOwner, newOrdinal, suppressOptional: true) { } internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath; internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber; internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName; // We don't currently support caller argument expression for cloned begin/end invoke since // they throw PlatformNotSupportedException at runtime and we feel it's unnecessary to support them. internal override int CallerArgumentExpressionParameterIndex => -1; internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke( _originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), (SourceDelegateMethodSymbol)ContainingSymbol, Ordinal); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceDelegateClonedParameterSymbolForBeginAndEndInvoke : SourceClonedParameterSymbol { internal SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(SourceParameterSymbol originalParam, SourceDelegateMethodSymbol newOwner, int newOrdinal) : base(originalParam, newOwner, newOrdinal, suppressOptional: true) { } internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath; internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber; internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName; // We don't currently support caller argument expression for cloned begin/end invoke since // they throw PlatformNotSupportedException at runtime and we feel it's unnecessary to support them. internal override int CallerArgumentExpressionParameterIndex => -1; internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke( _originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), (SourceDelegateMethodSymbol)ContainingSymbol, Ordinal); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Emit/CodeGen/SwitchTests.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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class SwitchTests : EmitMetadataTestBase { #region Functionality tests [Fact] public void DefaultOnlySwitch() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { default: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }"); } [WorkItem(542298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542298")] [Fact] public void DefaultOnlySwitch_02() { string text = @"using System; public class Test { public static void Main() { int status = 2; switch (status) { default: status--; break; } string str = ""string""; switch (str) { default: status--; break; } Console.WriteLine(status); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.1 IL_0004: sub IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }" ); } [Fact] public void ConstantIntegerSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { case true: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }" ); } [Fact] public void ConstantNullSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; const string s = null; switch (s) { case null: ret = 0; break; } Console.Write(ret); return(ret); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }" ); } [Fact] public void NonConstantSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; int value = 1; switch (value) { case 2: ret = 1; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: bne.un.s IL_0008 IL_0006: ldc.i4.1 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""void System.Console.Write(int)"" IL_000e: ldloc.0 IL_000f: ret }" ); } [Fact] public void ConstantVariableInCaseLabel() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; int value = 23; switch (value) { case kValue: ret = 0; break; default: ret = 1; break; } Console.Write(ret); return(ret); } const int kValue = 23; }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.s 23 IL_0004: ldc.i4.s 23 IL_0006: bne.un.s IL_000c IL_0008: ldc.i4.0 IL_0009: stloc.0 IL_000a: br.s IL_000e IL_000c: ldc.i4.1 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void System.Console.Write(int)"" IL_0014: ldloc.0 IL_0015: ret }" ); } [Fact] public void DefaultExpressionInLabel() { var source = @" class C { static void Main() { switch (0) { case default(int): return; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void SwitchWith_NoMatchingCaseLabel_And_NoDefaultLabel() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case 1: case 2: case 3: return 1; case 1001: case 1002: case 1003: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: ldc.i4.2 IL_0006: ble.un.s IL_0014 IL_0008: ldloc.0 IL_0009: ldc.i4 0x3e9 IL_000e: sub IL_000f: ldc.i4.2 IL_0010: ble.un.s IL_0016 IL_0012: br.s IL_0018 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.2 IL_0017: ret IL_0018: ldc.i4.0 IL_0019: ret }" ); } [Fact] public void DegenerateSwitch001() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(100); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; case 100: goto case 3; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.6 IL_0002: ble.un.s IL_0009 IL_0004: ldarg.0 IL_0005: ldc.i4.s 100 IL_0007: bne.un.s IL_000b IL_0009: ldc.i4.1 IL_000a: ret IL_000b: ldc.i4.0 IL_000c: ret }" ); } [Fact] public void DegenerateSwitch001_Debug() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(100); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; case 100: goto case 3; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1", options: TestOptions.DebugExe); compVerifier.VerifyIL("Test.M", @" { // Code size 30 (0x1e) .maxstack 2 .locals init (int V_0, int V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: stloc.0 IL_0005: ldloc.0 IL_0006: ldc.i4.6 IL_0007: ble.un.s IL_0012 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ldc.i4.s 100 IL_000e: beq.s IL_0016 IL_0010: br.s IL_0018 IL_0012: ldc.i4.1 IL_0013: stloc.2 IL_0014: br.s IL_001c IL_0016: br.s IL_0012 IL_0018: ldc.i4.0 IL_0019: stloc.2 IL_001a: br.s IL_001c IL_001c: ldloc.2 IL_001d: ret }" ); } [Fact] public void DegenerateSwitch002() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(5); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.5 IL_0004: bgt.un.s IL_0008 IL_0006: ldc.i4.1 IL_0007: ret IL_0008: ldc.i4.0 IL_0009: ret } " ); } [Fact] public void DegenerateSwitch003() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(4); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case -2: case -1: case 0: case 2: case 1: case 4: case 3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s -2 IL_0003: sub IL_0004: ldc.i4.6 IL_0005: bgt.un.s IL_0009 IL_0007: ldc.i4.1 IL_0008: ret IL_0009: ldc.i4.0 IL_000a: ret }" ); } [Fact] public void DegenerateSwitch004() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(int.MaxValue - 1); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case int.MinValue + 1: case int.MinValue: case int.MaxValue: case int.MaxValue - 1: case int.MaxValue - 2: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x80000000 IL_0006: sub IL_0007: ldc.i4.1 IL_0008: ble.un.s IL_0014 IL_000a: ldarg.0 IL_000b: ldc.i4 0x7ffffffd IL_0010: sub IL_0011: ldc.i4.2 IL_0012: bgt.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } [Fact] public void DegenerateSwitch005() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(int.MaxValue + 1L); Console.Write(ret); return(ret); } public static int M(long i) { switch (i) { case int.MaxValue: case int.MaxValue + 1L: case int.MaxValue + 2L: case int.MaxValue + 3L: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x7fffffff IL_0006: conv.i8 IL_0007: sub IL_0008: ldc.i4.3 IL_0009: conv.i8 IL_000a: bgt.un.s IL_000e IL_000c: ldc.i4.1 IL_000d: ret IL_000e: ldc.i4.0 IL_000f: ret }" ); } [Fact] public void DegenerateSwitch006() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(35); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; case 31: case 35: case 36: case 33: case 34: case 32: return 4; case 41: case 45: case 46: case 43: case 44: case 42: return 5; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "4"); compVerifier.VerifyIL("Test.M", @" { // Code size 30 (0x1e) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.5 IL_0004: ble.un.s IL_0016 IL_0006: ldarg.0 IL_0007: ldc.i4.s 31 IL_0009: sub IL_000a: ldc.i4.5 IL_000b: ble.un.s IL_0018 IL_000d: ldarg.0 IL_000e: ldc.i4.s 41 IL_0010: sub IL_0011: ldc.i4.5 IL_0012: ble.un.s IL_001a IL_0014: br.s IL_001c IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldc.i4.4 IL_0019: ret IL_001a: ldc.i4.5 IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }" ); } [Fact] public void NotDegenerateSwitch006() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(35); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; case 11: case 15: case 16: case 13: case 14: case 12: return 2; case 21: case 25: case 26: case 23: case 24: case 22: return 3; case 31: case 35: case 36: case 33: case 34: case 32: return 4; case 41: case 45: case 46: case 43: case 44: case 42: return 5; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "4"); compVerifier.VerifyIL("Test.M", @" { // Code size 206 (0xce) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: switch ( IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00ca, IL_00ca, IL_00ca, IL_00ca, IL_00ca, IL_00ca) IL_00c0: br.s IL_00cc IL_00c2: ldc.i4.1 IL_00c3: ret IL_00c4: ldc.i4.2 IL_00c5: ret IL_00c6: ldc.i4.3 IL_00c7: ret IL_00c8: ldc.i4.4 IL_00c9: ret IL_00ca: ldc.i4.5 IL_00cb: ret IL_00cc: ldc.i4.0 IL_00cd: ret }"); } [Fact] public void DegenerateSwitch007() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(5); Console.Write(ret); return(ret); } public static int M(int? i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; default: return 0; case null: return 2; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (int V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0019 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldc.i4.6 IL_0013: bgt.un.s IL_0017 IL_0015: ldc.i4.1 IL_0016: ret IL_0017: ldc.i4.0 IL_0018: ret IL_0019: ldc.i4.2 IL_001a: ret }" ); } [Fact] public void DegenerateSwitch008() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M((uint)int.MaxValue + (uint)1); Console.Write(ret); return(ret); } public static int M(uint i) { switch (i) { case (uint)int.MaxValue: case (uint)int.MaxValue + (uint)1: case (uint)int.MaxValue + (uint)2: case (uint)int.MaxValue + (uint)3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x7fffffff IL_0006: sub IL_0007: ldc.i4.3 IL_0008: bgt.un.s IL_000c IL_000a: ldc.i4.1 IL_000b: ret IL_000c: ldc.i4.0 IL_000d: ret }" ); } [Fact] public void DegenerateSwitch009() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(uint.MaxValue); Console.Write(ret); return(ret); } public static int M(uint i) { switch (i) { case 0: case 1: case uint.MaxValue: case uint.MaxValue - 1: case uint.MaxValue - 2: case uint.MaxValue - 3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ble.un.s IL_000b IL_0004: ldarg.0 IL_0005: ldc.i4.s -4 IL_0007: sub IL_0008: ldc.i4.3 IL_0009: bgt.un.s IL_000d IL_000b: ldc.i4.1 IL_000c: ret IL_000d: ldc.i4.0 IL_000e: ret }" ); } [Fact] public void ByteTypeSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; ret = DoByte(); return(ret); } private static int DoByte() { int ret = 2; byte b = 2; switch (b) { case 1: case 2: ret--; break; case 3: break; default: break; } switch (b) { case 1: case 3: break; default: ret--; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoByte", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, //ret byte V_1) //b IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloc.1 IL_0005: ldc.i4.1 IL_0006: sub IL_0007: ldc.i4.1 IL_0008: ble.un.s IL_0010 IL_000a: ldloc.1 IL_000b: ldc.i4.3 IL_000c: beq.s IL_0014 IL_000e: br.s IL_0014 IL_0010: ldloc.0 IL_0011: ldc.i4.1 IL_0012: sub IL_0013: stloc.0 IL_0014: ldloc.1 IL_0015: ldc.i4.1 IL_0016: beq.s IL_0020 IL_0018: ldloc.1 IL_0019: ldc.i4.3 IL_001a: beq.s IL_0020 IL_001c: ldloc.0 IL_001d: ldc.i4.1 IL_001e: sub IL_001f: stloc.0 IL_0020: ldloc.0 IL_0021: call ""void System.Console.Write(int)"" IL_0026: ldloc.0 IL_0027: ret }" ); } [Fact] public void LongTypeSwitchArgumentExpression() { var text = @" using System; public class Test { public static void Main(string [] args) { int ret = 0; ret = DoLong(2); Console.Write(ret); ret = DoLong(4); Console.Write(ret); ret = DoLong(42); Console.Write(ret); } private static int DoLong(long b) { int ret = 2; switch (b) { case 1: ret++; break; case 2: ret--; break; case 3: break; case 4: ret += 7; break; default: ret+=2; break; } return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "194"); compVerifier.VerifyIL("Test.DoLong", @" { // Code size 62 (0x3e) .maxstack 3 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldc.i4.1 IL_0004: conv.i8 IL_0005: sub IL_0006: dup IL_0007: ldc.i4.3 IL_0008: conv.i8 IL_0009: ble.un.s IL_000e IL_000b: pop IL_000c: br.s IL_0038 IL_000e: conv.u4 IL_000f: switch ( IL_0026, IL_002c, IL_003c, IL_0032) IL_0024: br.s IL_0038 IL_0026: ldloc.0 IL_0027: ldc.i4.1 IL_0028: add IL_0029: stloc.0 IL_002a: br.s IL_003c IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: sub IL_002f: stloc.0 IL_0030: br.s IL_003c IL_0032: ldloc.0 IL_0033: ldc.i4.7 IL_0034: add IL_0035: stloc.0 IL_0036: br.s IL_003c IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: add IL_003b: stloc.0 IL_003c: ldloc.0 IL_003d: ret }" ); } [WorkItem(740058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740058")] [Fact] public void LongTypeSwitchArgumentExpressionOverflow() { var text = @" using System; public class Test { public static void Main(string[] args) { string ret; ret = DoLong(long.MaxValue); Console.Write(ret); ret = DoLong(long.MinValue); Console.Write(ret); ret = DoLong(1L); Console.Write(ret); ret = DoLong(0L); Console.Write(ret); } private static string DoLong(long b) { switch (b) { case long.MaxValue: return ""max""; case 1L: return ""one""; case long.MinValue: return ""min""; default: return ""default""; } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "maxminonedefault"); compVerifier.VerifyIL("Test.DoLong", @" { // Code size 53 (0x35) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i8 0x8000000000000000 IL_000a: beq.s IL_0029 IL_000c: ldarg.0 IL_000d: ldc.i4.1 IL_000e: conv.i8 IL_000f: beq.s IL_0023 IL_0011: ldarg.0 IL_0012: ldc.i8 0x7fffffffffffffff IL_001b: bne.un.s IL_002f IL_001d: ldstr ""max"" IL_0022: ret IL_0023: ldstr ""one"" IL_0028: ret IL_0029: ldstr ""min"" IL_002e: ret IL_002f: ldstr ""default"" IL_0034: ret }" ); } [Fact] public void ULongTypeSwitchArgumentExpression() { var text = @" using System; public class Test { public static void Main(string[] args) { int ret = 0; ret = DoULong(0x1000000000000001L); Console.Write(ret); } private static int DoULong(ulong b) { int ret = 2; switch (b) { case 0: ret++; break; case 1: ret--; break; case 2: break; case 3: ret += 7; break; default: ret += 40; break; } return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "42"); compVerifier.VerifyIL("Test.DoULong", @" { // Code size 60 (0x3c) .maxstack 3 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: dup IL_0004: ldc.i4.3 IL_0005: conv.i8 IL_0006: ble.un.s IL_000b IL_0008: pop IL_0009: br.s IL_0035 IL_000b: conv.u4 IL_000c: switch ( IL_0023, IL_0029, IL_003a, IL_002f) IL_0021: br.s IL_0035 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: br.s IL_003a IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: sub IL_002c: stloc.0 IL_002d: br.s IL_003a IL_002f: ldloc.0 IL_0030: ldc.i4.7 IL_0031: add IL_0032: stloc.0 IL_0033: br.s IL_003a IL_0035: ldloc.0 IL_0036: ldc.i4.s 40 IL_0038: add IL_0039: stloc.0 IL_003a: ldloc.0 IL_003b: ret }" ); } [Fact] public void EnumTypeSwitchArgumentExpressionWithCasts() { var text = @"using System; public class Test { enum eTypes { kFirst, kSecond, kThird, }; public static int Main(string [] args) { int ret = 0; ret = DoEnum(); return(ret); } private static int DoEnum() { int ret = 2; eTypes e = eTypes.kSecond; switch (e) { case eTypes.kThird: case eTypes.kSecond: ret--; break; case (eTypes) (-1): break; default: break; } switch (e) { case (eTypes)100: case (eTypes) (-1): break; default: ret--; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoEnum", @" { // Code size 39 (0x27) .maxstack 2 .locals init (int V_0, //ret Test.eTypes V_1) //e IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldloc.1 IL_0005: ldc.i4.m1 IL_0006: beq.s IL_0012 IL_0008: ldloc.1 IL_0009: ldc.i4.1 IL_000a: sub IL_000b: ldc.i4.1 IL_000c: bgt.un.s IL_0012 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: sub IL_0011: stloc.0 IL_0012: ldloc.1 IL_0013: ldc.i4.m1 IL_0014: beq.s IL_001f IL_0016: ldloc.1 IL_0017: ldc.i4.s 100 IL_0019: beq.s IL_001f IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: sub IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldloc.0 IL_0026: ret }" ); } [Fact] public void NullableEnumTypeSwitchArgumentExpression() { var text = @"using System; public class Test { enum eTypes { kFirst, kSecond, kThird, }; public static int Main(string [] args) { int ret = 0; ret = DoEnum(); return(ret); } private static int DoEnum() { int ret = 3; eTypes? e = eTypes.kSecond; switch (e) { case eTypes.kThird: case eTypes.kSecond: ret--; break; default: break; } switch (e) { case null: case (eTypes) (-1): break; default: ret--; break; } e = null; switch (e) { case null: ret--; break; case (eTypes) (-1): case eTypes.kThird: case eTypes.kSecond: default: break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoEnum", @" { // Code size 109 (0x6d) .maxstack 2 .locals init (int V_0, //ret Test.eTypes? V_1, //e Test.eTypes V_2) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: call ""Test.eTypes?..ctor(Test.eTypes)"" IL_000a: ldloca.s V_1 IL_000c: call ""bool Test.eTypes?.HasValue.get"" IL_0011: brfalse.s IL_0025 IL_0013: ldloca.s V_1 IL_0015: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_001a: stloc.2 IL_001b: ldloc.2 IL_001c: ldc.i4.1 IL_001d: sub IL_001e: ldc.i4.1 IL_001f: bgt.un.s IL_0025 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: sub IL_0024: stloc.0 IL_0025: ldloca.s V_1 IL_0027: call ""bool Test.eTypes?.HasValue.get"" IL_002c: brfalse.s IL_003c IL_002e: ldloca.s V_1 IL_0030: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_0035: ldc.i4.m1 IL_0036: beq.s IL_003c IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: sub IL_003b: stloc.0 IL_003c: ldloca.s V_1 IL_003e: initobj ""Test.eTypes?"" IL_0044: ldloca.s V_1 IL_0046: call ""bool Test.eTypes?.HasValue.get"" IL_004b: brfalse.s IL_0061 IL_004d: ldloca.s V_1 IL_004f: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_0054: stloc.2 IL_0055: ldloc.2 IL_0056: ldc.i4.m1 IL_0057: beq.s IL_0065 IL_0059: ldloc.2 IL_005a: ldc.i4.1 IL_005b: sub IL_005c: ldc.i4.1 IL_005d: ble.un.s IL_0065 IL_005f: br.s IL_0065 IL_0061: ldloc.0 IL_0062: ldc.i4.1 IL_0063: sub IL_0064: stloc.0 IL_0065: ldloc.0 IL_0066: call ""void System.Console.Write(int)"" IL_006b: ldloc.0 IL_006c: ret }"); } [Fact] public void SwitchSectionWithGotoNonSwitchLabel() { var text = @" class Test { public static int Main() { int ret = 1; switch (10) { case 123: // No unreachable code warning here mylabel: --ret; break; case 9: // No unreachable code warning here case 10: case 11: // No unreachable code warning here goto mylabel; } System.Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics(); compVerifier.VerifyIL("Test.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""void System.Console.Write(int)"" IL_000c: ldloc.0 IL_000d: ret }" ); } [Fact] public void SwitchSectionWithGotoNonSwitchLabel_02() { var text = @"class Test { delegate void D(); public static void Main() { int i = 0; switch (10) { case 5: goto mylabel; case 10: goto case 5; case 15: mylabel: D d1 = delegate() { System.Console.Write(i); }; d1(); return; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (Test.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Test.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld ""int Test.<>c__DisplayClass1_0.i"" IL_000d: ldloc.0 IL_000e: ldftn ""void Test.<>c__DisplayClass1_0.<Main>b__0()"" IL_0014: newobj ""Test.D..ctor(object, System.IntPtr)"" IL_0019: callvirt ""void Test.D.Invoke()"" IL_001e: ret } " ); } [Fact] public void SwitchSectionWithReturnStatement() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 3; for (int i = 0; i < 3; i++) { switch (i) { case 1: case 0: case 2: ret--; break; default: Console.Write(1); return(1); } } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, //ret int V_1) //i IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_001c IL_0006: ldloc.1 IL_0007: ldc.i4.2 IL_0008: bgt.un.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: sub IL_000d: stloc.0 IL_000e: br.s IL_0018 IL_0010: ldc.i4.1 IL_0011: call ""void System.Console.Write(int)"" IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldloc.1 IL_0019: ldc.i4.1 IL_001a: add IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.3 IL_001e: blt.s IL_0006 IL_0020: ldloc.0 IL_0021: call ""void System.Console.Write(int)"" IL_0026: ldloc.0 IL_0027: ret }" ); } [Fact] public void SwitchSectionWithReturnStatement_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case 1: return 1; } return 0; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_0006 IL_0004: ldc.i4.1 IL_0005: ret IL_0006: ldc.i4.0 IL_0007: ret }" ); } [Fact] public void CaseLabelWithTypeCastToGoverningType() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case (int) 5.0f: return 0; default: return 1; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.5 IL_0002: bne.un.s IL_0006 IL_0004: ldc.i4.0 IL_0005: ret IL_0006: ldc.i4.1 IL_0007: ret }" ); } [Fact] public void SwitchSectionWithTryFinally() { var text = @"using System; class Class1 { static int Main() { int j = 0; int i = 3; switch (j) { case 0: try { i = 0; } catch { i = 1; } finally { j = 2; } break; default: i = 2; break; } Console.Write(i); return i; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Class1.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: ldc.i4.3 IL_0002: stloc.0 IL_0003: brtrue.s IL_0010 IL_0005: nop .try { .try { IL_0006: ldc.i4.0 IL_0007: stloc.0 IL_0008: leave.s IL_0012 } catch object { IL_000a: pop IL_000b: ldc.i4.1 IL_000c: stloc.0 IL_000d: leave.s IL_0012 } } finally { IL_000f: endfinally } IL_0010: ldc.i4.2 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ret }" ); } [Fact] public void MultipleSwitchSectionsWithGotoCase() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int ret = 6; switch (ret) { case 0: ret--; // 2 Console.Write(""case 0: ""); Console.WriteLine(ret); goto case 9999; case 2: ret--; // 4 Console.Write(""case 2: ""); Console.WriteLine(ret); goto case 255; case 6: // start here ret--; // 5 Console.Write(""case 5: ""); Console.WriteLine(ret); goto case 2; case 9999: ret--; // 1 Console.Write(""case 9999: ""); Console.WriteLine(ret); goto default; case 0xff: ret--; // 3 Console.Write(""case 0xff: ""); Console.WriteLine(ret); goto case 0; default: ret--; Console.Write(""Default: ""); Console.WriteLine(ret); if (ret > 0) { goto case -1; } break; case -1: ret = 999; Console.WriteLine(""case -1: ""); Console.Write(ret); break; } return(ret); } }"; string expectedOutput = @"case 5: 5 case 2: 4 case 0xff: 3 case 0: 2 case 9999: 1 Default: 0 0"; var compVerifier = CompileAndVerify(text, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.M", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.6 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.6 IL_0004: bgt.s IL_0027 IL_0006: ldloc.0 IL_0007: ldc.i4.m1 IL_0008: sub IL_0009: switch ( IL_00bf, IL_0039, IL_00a7, IL_004f) IL_001e: ldloc.0 IL_001f: ldc.i4.6 IL_0020: beq.s IL_0065 IL_0022: br IL_00a7 IL_0027: ldloc.0 IL_0028: ldc.i4 0xff IL_002d: beq.s IL_0091 IL_002f: ldloc.0 IL_0030: ldc.i4 0x270f IL_0035: beq.s IL_007b IL_0037: br.s IL_00a7 IL_0039: ldloc.0 IL_003a: ldc.i4.1 IL_003b: sub IL_003c: stloc.0 IL_003d: ldstr ""case 0: "" IL_0042: call ""void System.Console.Write(string)"" IL_0047: ldloc.0 IL_0048: call ""void System.Console.WriteLine(int)"" IL_004d: br.s IL_007b IL_004f: ldloc.0 IL_0050: ldc.i4.1 IL_0051: sub IL_0052: stloc.0 IL_0053: ldstr ""case 2: "" IL_0058: call ""void System.Console.Write(string)"" IL_005d: ldloc.0 IL_005e: call ""void System.Console.WriteLine(int)"" IL_0063: br.s IL_0091 IL_0065: ldloc.0 IL_0066: ldc.i4.1 IL_0067: sub IL_0068: stloc.0 IL_0069: ldstr ""case 5: "" IL_006e: call ""void System.Console.Write(string)"" IL_0073: ldloc.0 IL_0074: call ""void System.Console.WriteLine(int)"" IL_0079: br.s IL_004f IL_007b: ldloc.0 IL_007c: ldc.i4.1 IL_007d: sub IL_007e: stloc.0 IL_007f: ldstr ""case 9999: "" IL_0084: call ""void System.Console.Write(string)"" IL_0089: ldloc.0 IL_008a: call ""void System.Console.WriteLine(int)"" IL_008f: br.s IL_00a7 IL_0091: ldloc.0 IL_0092: ldc.i4.1 IL_0093: sub IL_0094: stloc.0 IL_0095: ldstr ""case 0xff: "" IL_009a: call ""void System.Console.Write(string)"" IL_009f: ldloc.0 IL_00a0: call ""void System.Console.WriteLine(int)"" IL_00a5: br.s IL_0039 IL_00a7: ldloc.0 IL_00a8: ldc.i4.1 IL_00a9: sub IL_00aa: stloc.0 IL_00ab: ldstr ""Default: "" IL_00b0: call ""void System.Console.Write(string)"" IL_00b5: ldloc.0 IL_00b6: call ""void System.Console.WriteLine(int)"" IL_00bb: ldloc.0 IL_00bc: ldc.i4.0 IL_00bd: ble.s IL_00d5 IL_00bf: ldc.i4 0x3e7 IL_00c4: stloc.0 IL_00c5: ldstr ""case -1: "" IL_00ca: call ""void System.Console.WriteLine(string)"" IL_00cf: ldloc.0 IL_00d0: call ""void System.Console.Write(int)"" IL_00d5: ldloc.0 IL_00d6: ret }" ); } [Fact] public void Switch_TestSwitchBuckets_01() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 0; // Expected switch buckets: (10, 12, 14) (1000) (2000, 2001, 2005, 2008, 2009, 2010) switch (i) { case 10: case 2000: case 12: return 1; case 2001: case 14: return 2; case 1000: case 2010: case 2008: return 3; case 2005: case 2009: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 107 (0x6b) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.s 10 IL_0005: sub IL_0006: switch ( IL_0061, IL_0069, IL_0061, IL_0069, IL_0063) IL_001f: ldloc.0 IL_0020: ldc.i4 0x3e8 IL_0025: beq.s IL_0065 IL_0027: ldloc.0 IL_0028: ldc.i4 0x7d0 IL_002d: sub IL_002e: switch ( IL_0061, IL_0063, IL_0069, IL_0069, IL_0069, IL_0067, IL_0069, IL_0069, IL_0065, IL_0067, IL_0065) IL_005f: br.s IL_0069 IL_0061: ldc.i4.1 IL_0062: ret IL_0063: ldc.i4.2 IL_0064: ret IL_0065: ldc.i4.3 IL_0066: ret IL_0067: ldc.i4.2 IL_0068: ret IL_0069: ldc.i4.0 IL_006a: ret }" ); } [Fact] public void Switch_TestSwitchBuckets_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 0; // Expected switch buckets: (10, 12, 14) (1000) (2000, 2001) (2008, 2009, 2010) switch (i) { case 10: case 2000: case 12: return 1; case 2001: case 14: return 2; case 1000: case 2010: case 2008: return 3; case 2009: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 101 (0x65) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4 0x3e8 IL_0008: bgt.s IL_0031 IL_000a: ldloc.0 IL_000b: ldc.i4.s 10 IL_000d: sub IL_000e: switch ( IL_005b, IL_0063, IL_005b, IL_0063, IL_005d) IL_0027: ldloc.0 IL_0028: ldc.i4 0x3e8 IL_002d: beq.s IL_005f IL_002f: br.s IL_0063 IL_0031: ldloc.0 IL_0032: ldc.i4 0x7d0 IL_0037: beq.s IL_005b IL_0039: ldloc.0 IL_003a: ldc.i4 0x7d1 IL_003f: beq.s IL_005d IL_0041: ldloc.0 IL_0042: ldc.i4 0x7d8 IL_0047: sub IL_0048: switch ( IL_005f, IL_0061, IL_005f) IL_0059: br.s IL_0063 IL_005b: ldc.i4.1 IL_005c: ret IL_005d: ldc.i4.2 IL_005e: ret IL_005f: ldc.i4.3 IL_0060: ret IL_0061: ldc.i4.2 IL_0062: ret IL_0063: ldc.i4.0 IL_0064: ret }" ); } [WorkItem(542398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542398")] [Fact] public void MaxValueGotoCaseExpression() { var text = @" class Program { static void Main(string[] args) { ulong a = 0; switch (a) { case long.MaxValue: goto case ulong.MaxValue; case ulong.MaxValue: break; } } } "; CompileAndVerify(text, expectedOutput: ""); } [WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")] [Fact()] public void NullableAsSwitchExpression() { var text = @"using System; class Program { static void Main() { sbyte? local = null; switch (local) { case null: Console.Write(""null ""); break; case 1: Console.Write(""1 ""); break; } Goo(1); } static void Goo(sbyte? p) { switch (p) { case 1: Console.Write(""1 ""); break; case null: Console.Write(""null ""); break; } } } "; var verifier = CompileAndVerify(text, expectedOutput: "null 1"); verifier.VerifyIL("Program.Main", @" { // Code size 64 (0x40) .maxstack 2 .locals init (sbyte? V_0) //local IL_0000: ldloca.s V_0 IL_0002: initobj ""sbyte?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool sbyte?.HasValue.get"" IL_000f: brfalse.s IL_001d IL_0011: ldloca.s V_0 IL_0013: call ""sbyte sbyte?.GetValueOrDefault()"" IL_0018: ldc.i4.1 IL_0019: beq.s IL_0029 IL_001b: br.s IL_0033 IL_001d: ldstr ""null "" IL_0022: call ""void System.Console.Write(string)"" IL_0027: br.s IL_0033 IL_0029: ldstr ""1 "" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldc.i4.1 IL_0034: conv.i1 IL_0035: newobj ""sbyte?..ctor(sbyte)"" IL_003a: call ""void Program.Goo(sbyte?)"" IL_003f: ret }"); } [WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")] [Fact()] public void NullableAsSwitchExpression_02() { var text = @"using System; class Program { static void Main() { Goo(null); Goo(100); } static void Goo(short? p) { switch (p) { case null: Console.Write(""null ""); break; case 1: break; case 2: break; case 3: break; case 100: Console.Write(""100 ""); break; case 101: break; case 103: break; case 1001: break; case 1002: break; case 1003: break; } switch (p) { case 1: break; case 2: break; case 3: break; case 101: break; case 103: break; case 1001: break; case 1002: break; case 1003: break; default: Console.Write(""default ""); break; } switch (p) { case 1: Console.Write(""FAIL""); break; case 2: Console.Write(""FAIL""); break; case 3: Console.Write(""FAIL""); break; case 101: Console.Write(""FAIL""); break; case 103: Console.Write(""FAIL""); break; case 1001: Console.Write(""FAIL""); break; case 1002: Console.Write(""FAIL""); break; case 1003: Console.Write(""FAIL""); break; } } } "; var verifier = CompileAndVerify(text, expectedOutput: "null default 100 default "); verifier.VerifyIL("Program.Goo", @" { // Code size 367 (0x16f) .maxstack 2 .locals init (short V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool short?.HasValue.get"" IL_0007: brfalse.s IL_0058 IL_0009: ldarga.s V_0 IL_000b: call ""short short?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldc.i4.1 IL_0013: sub IL_0014: switch ( IL_006e, IL_006e, IL_006e) IL_0025: ldloc.0 IL_0026: ldc.i4.s 100 IL_0028: sub IL_0029: switch ( IL_0064, IL_006e, IL_006e, IL_006e) IL_003e: ldloc.0 IL_003f: ldc.i4 0x3e9 IL_0044: sub IL_0045: switch ( IL_006e, IL_006e, IL_006e) IL_0056: br.s IL_006e IL_0058: ldstr ""null "" IL_005d: call ""void System.Console.Write(string)"" IL_0062: br.s IL_006e IL_0064: ldstr ""100 "" IL_0069: call ""void System.Console.Write(string)"" IL_006e: ldarga.s V_0 IL_0070: call ""bool short?.HasValue.get"" IL_0075: brfalse.s IL_00bc IL_0077: ldarga.s V_0 IL_0079: call ""short short?.GetValueOrDefault()"" IL_007e: stloc.0 IL_007f: ldloc.0 IL_0080: ldc.i4.s 101 IL_0082: bgt.s IL_009f IL_0084: ldloc.0 IL_0085: ldc.i4.1 IL_0086: sub IL_0087: switch ( IL_00c6, IL_00c6, IL_00c6) IL_0098: ldloc.0 IL_0099: ldc.i4.s 101 IL_009b: beq.s IL_00c6 IL_009d: br.s IL_00bc IL_009f: ldloc.0 IL_00a0: ldc.i4.s 103 IL_00a2: beq.s IL_00c6 IL_00a4: ldloc.0 IL_00a5: ldc.i4 0x3e9 IL_00aa: sub IL_00ab: switch ( IL_00c6, IL_00c6, IL_00c6) IL_00bc: ldstr ""default "" IL_00c1: call ""void System.Console.Write(string)"" IL_00c6: ldarga.s V_0 IL_00c8: call ""bool short?.HasValue.get"" IL_00cd: brfalse IL_016e IL_00d2: ldarga.s V_0 IL_00d4: call ""short short?.GetValueOrDefault()"" IL_00d9: stloc.0 IL_00da: ldloc.0 IL_00db: ldc.i4.s 101 IL_00dd: bgt.s IL_00f9 IL_00df: ldloc.0 IL_00e0: ldc.i4.1 IL_00e1: sub IL_00e2: switch ( IL_0117, IL_0122, IL_012d) IL_00f3: ldloc.0 IL_00f4: ldc.i4.s 101 IL_00f6: beq.s IL_0138 IL_00f8: ret IL_00f9: ldloc.0 IL_00fa: ldc.i4.s 103 IL_00fc: beq.s IL_0143 IL_00fe: ldloc.0 IL_00ff: ldc.i4 0x3e9 IL_0104: sub IL_0105: switch ( IL_014e, IL_0159, IL_0164) IL_0116: ret IL_0117: ldstr ""FAIL"" IL_011c: call ""void System.Console.Write(string)"" IL_0121: ret IL_0122: ldstr ""FAIL"" IL_0127: call ""void System.Console.Write(string)"" IL_012c: ret IL_012d: ldstr ""FAIL"" IL_0132: call ""void System.Console.Write(string)"" IL_0137: ret IL_0138: ldstr ""FAIL"" IL_013d: call ""void System.Console.Write(string)"" IL_0142: ret IL_0143: ldstr ""FAIL"" IL_0148: call ""void System.Console.Write(string)"" IL_014d: ret IL_014e: ldstr ""FAIL"" IL_0153: call ""void System.Console.Write(string)"" IL_0158: ret IL_0159: ldstr ""FAIL"" IL_015e: call ""void System.Console.Write(string)"" IL_0163: ret IL_0164: ldstr ""FAIL"" IL_0169: call ""void System.Console.Write(string)"" IL_016e: ret }"); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableInt64WithInt32Label() { var text = @"public static class C { public static bool F(long? x) { switch (x) { case 1: return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "True"); compVerifier.VerifyIL("C.F(long?)", @"{ // Code size 24 (0x18) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool long?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""long long?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: conv.i8 IL_0012: bne.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableWithNonConstant() { var text = @"public static class C { public static bool F(int? x) { int i = 4; switch (x) { case i: return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compilation = base.CreateCSharpCompilation(text); compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case i: Diagnostic(ErrorCode.ERR_ConstantExpected, "i").WithLocation(8, 18) ); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableWithNonCompatibleType() { var text = @"public static class C { public static bool F(int? x) { switch (x) { case default(System.DateTime): return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compilation = base.CreateCSharpCompilation(text); // (7,18): error CS0029: Cannot implicitly convert type 'System.DateTime' to 'int?' // case default(System.DateTime): var expected = Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(System.DateTime)").WithArguments("System.DateTime", "int?"); compilation.VerifyDiagnostics(expected); } [Fact] public void SwitchOnNullableInt64WithInt32LabelWithEnum() { var text = @"public static class C { public static bool F(long? x) { switch (x) { case (int)Goo.X: return true; default: return false; } } public enum Goo : int { X = 1 } static void Main() { System.Console.WriteLine(F(1)); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "True"); compVerifier.VerifyIL("C.F(long?)", @"{ // Code size 24 (0x18) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool long?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""long long?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: conv.i8 IL_0012: bne.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } // TODO: Add more targeted tests for verifying switch bucketing #region "String tests" [Fact] public void StringTypeSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { string s = ""hello""; switch (s) { default: return 1; case null: return 1; case ""hello"": return 0; } return 1; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (25,5): warning CS0162: Unreachable code detected // return 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); compVerifier.VerifyIL("Test.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //s IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0018 IL_0009: ldloc.0 IL_000a: ldstr ""hello"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_001a IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }" ); // We shouldn't generate a string hash synthesized method if we are generating non hash string switch VerifySynthesizedStringHashMethod(compVerifier, expected: false); } [Fact] public void StringSwitch_SwitchOnNull() { var text = @"using System; public class Test { public static int Main(string[] args) { string s = null; int ret = 0; switch (s) { case null + ""abc"": ret = 1; break; case null + ""def"": ret = 1; break; } Console.Write(ret); return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (string V_0, //s int V_1) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldstr ""abc"" IL_000a: call ""bool string.op_Equality(string, string)"" IL_000f: brtrue.s IL_0020 IL_0011: ldloc.0 IL_0012: ldstr ""def"" IL_0017: call ""bool string.op_Equality(string, string)"" IL_001c: brtrue.s IL_0024 IL_001e: br.s IL_0026 IL_0020: ldc.i4.1 IL_0021: stloc.1 IL_0022: br.s IL_0026 IL_0024: ldc.i4.1 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldloc.1 IL_002d: ret }" ); // We shouldn't generate a string hash synthesized method if we are generating non hash string switch VerifySynthesizedStringHashMethod(compVerifier, expected: false); } [Fact] [WorkItem(546632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546632")] public void StringSwitch_HashTableSwitch_01() { var text = @"using System; class Test { public static bool M(string test) { string value = """"; if (test != null && test.IndexOf(""C#"") != -1) test = test.Remove(0, 2); switch (test) { case null: value = null; break; case """": break; case ""_"": value = ""_""; break; case ""W"": value = ""W""; break; case ""B"": value = ""B""; break; case ""C"": value = ""C""; break; case ""<"": value = ""<""; break; case ""T"": value = ""T""; break; case ""M"": value = ""M""; break; } return (value == test); } public static void Main() { bool success = Test.M(""C#""); success &= Test.M(""C#_""); success &= Test.M(""C#W""); success &= Test.M(""C#B""); success &= Test.M(""C#C""); success &= Test.M(""C#<""); success &= Test.M(""C#T""); success &= Test.M(""C#M""); success &= Test.M(null); Console.WriteLine(success); } }"; var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "True"); compVerifier.VerifyIL("Test.M", @" { // Code size 365 (0x16d) .maxstack 3 .locals init (string V_0, //value uint V_1) IL_0000: ldstr """" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: brfalse.s IL_0021 IL_0009: ldarg.0 IL_000a: ldstr ""C#"" IL_000f: callvirt ""int string.IndexOf(string)"" IL_0014: ldc.i4.m1 IL_0015: beq.s IL_0021 IL_0017: ldarg.0 IL_0018: ldc.i4.0 IL_0019: ldc.i4.2 IL_001a: callvirt ""string string.Remove(int, int)"" IL_001f: starg.s V_0 IL_0021: ldarg.0 IL_0022: brfalse IL_012b IL_0027: ldarg.0 IL_0028: call ""ComputeStringHash"" IL_002d: stloc.1 IL_002e: ldloc.1 IL_002f: ldc.i4 0xc70bfb85 IL_0034: bgt.un.s IL_006e IL_0036: ldloc.1 IL_0037: ldc.i4 0x811c9dc5 IL_003c: bgt.un.s IL_0056 IL_003e: ldloc.1 IL_003f: ldc.i4 0x390caefb IL_0044: beq IL_00fe IL_0049: ldloc.1 IL_004a: ldc.i4 0x811c9dc5 IL_004f: beq.s IL_00a6 IL_0051: br IL_0165 IL_0056: ldloc.1 IL_0057: ldc.i4 0xc60bf9f2 IL_005c: beq IL_00ef IL_0061: ldloc.1 IL_0062: ldc.i4 0xc70bfb85 IL_0067: beq.s IL_00e0 IL_0069: br IL_0165 IL_006e: ldloc.1 IL_006f: ldc.i4 0xd10c0b43 IL_0074: bgt.un.s IL_0091 IL_0076: ldloc.1 IL_0077: ldc.i4 0xc80bfd18 IL_007c: beq IL_011c IL_0081: ldloc.1 IL_0082: ldc.i4 0xd10c0b43 IL_0087: beq IL_010d IL_008c: br IL_0165 IL_0091: ldloc.1 IL_0092: ldc.i4 0xd20c0cd6 IL_0097: beq.s IL_00ce IL_0099: ldloc.1 IL_009a: ldc.i4 0xda0c196e IL_009f: beq.s IL_00bc IL_00a1: br IL_0165 IL_00a6: ldarg.0 IL_00a7: brfalse IL_0165 IL_00ac: ldarg.0 IL_00ad: call ""int string.Length.get"" IL_00b2: brfalse IL_0165 IL_00b7: br IL_0165 IL_00bc: ldarg.0 IL_00bd: ldstr ""_"" IL_00c2: call ""bool string.op_Equality(string, string)"" IL_00c7: brtrue.s IL_012f IL_00c9: br IL_0165 IL_00ce: ldarg.0 IL_00cf: ldstr ""W"" IL_00d4: call ""bool string.op_Equality(string, string)"" IL_00d9: brtrue.s IL_0137 IL_00db: br IL_0165 IL_00e0: ldarg.0 IL_00e1: ldstr ""B"" IL_00e6: call ""bool string.op_Equality(string, string)"" IL_00eb: brtrue.s IL_013f IL_00ed: br.s IL_0165 IL_00ef: ldarg.0 IL_00f0: ldstr ""C"" IL_00f5: call ""bool string.op_Equality(string, string)"" IL_00fa: brtrue.s IL_0147 IL_00fc: br.s IL_0165 IL_00fe: ldarg.0 IL_00ff: ldstr ""<"" IL_0104: call ""bool string.op_Equality(string, string)"" IL_0109: brtrue.s IL_014f IL_010b: br.s IL_0165 IL_010d: ldarg.0 IL_010e: ldstr ""T"" IL_0113: call ""bool string.op_Equality(string, string)"" IL_0118: brtrue.s IL_0157 IL_011a: br.s IL_0165 IL_011c: ldarg.0 IL_011d: ldstr ""M"" IL_0122: call ""bool string.op_Equality(string, string)"" IL_0127: brtrue.s IL_015f IL_0129: br.s IL_0165 IL_012b: ldnull IL_012c: stloc.0 IL_012d: br.s IL_0165 IL_012f: ldstr ""_"" IL_0134: stloc.0 IL_0135: br.s IL_0165 IL_0137: ldstr ""W"" IL_013c: stloc.0 IL_013d: br.s IL_0165 IL_013f: ldstr ""B"" IL_0144: stloc.0 IL_0145: br.s IL_0165 IL_0147: ldstr ""C"" IL_014c: stloc.0 IL_014d: br.s IL_0165 IL_014f: ldstr ""<"" IL_0154: stloc.0 IL_0155: br.s IL_0165 IL_0157: ldstr ""T"" IL_015c: stloc.0 IL_015d: br.s IL_0165 IL_015f: ldstr ""M"" IL_0164: stloc.0 IL_0165: ldloc.0 IL_0166: ldarg.0 IL_0167: call ""bool string.op_Equality(string, string)"" IL_016c: ret }" ); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); // verify that hash method is internal: var reference = compVerifier.Compilation.EmitToImageReference(); var comp = CSharpCompilation.Create("Name", references: new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var pid = ((NamedTypeSymbol)comp.GlobalNamespace.GetMembers().Single(s => s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); var member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single(); Assert.Equal(Accessibility.Internal, member.DeclaredAccessibility); } [Fact] public void StringSwitch_HashTableSwitch_02() { var text = @" using System; using System.Text; class Test { public static bool Switcheroo(string test) { string value = """"; if (test.IndexOf(""C#"") != -1) test = test.Remove(0, 2); switch (test) { case ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"": value = ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""; break; case ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"": value = ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""; break; case ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"": value = ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""; break; case ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"": value = ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""; break; case ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"": value = ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""; break; case ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"": value = ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""; break; case ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"": value = ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""; break; case ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"": value = ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""; break; case ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"": value = ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""; break; case ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"": value = ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""; break; case "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"": value = "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""; break; case ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"": value = ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""; break; case ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"": value = ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""; break; case ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"": value = ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""; break; case ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"": value = ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""; break; case ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"": value = ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""; break; case ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"": value = ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""; break; case ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"": value = ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""; break; case ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"": value = ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""; break; case ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"": value = ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""; break; case ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"": value = ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""; break; case ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"": value = ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""; break; case ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"": value = ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""; break; case ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"": value = ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""; break; } return (value == test); } public static void Main() { string status = ""PASS""; bool retval; retval = Test.Switcheroo(""C#N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#>AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#a@=FkgImdk5<Wn0DRYa?m0<F0JT4kha;H:HIZ;6C""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Zbk^]59O<<GHe8MjRMOh4]c3@RQ?hU>^G81cOMW:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#hP<l25H@W60UF4bYYDU]0AjIE6oCQ^k66F9gNJ`Q""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#XS9dCIb;9T`;JJ1Jmimba@@0[l[B=BgDhKZ05DO2""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#JbMbko?;e@1XLU>:=c_Vg>0YTJ7Qd]6KLh26miBV""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#IW3:>L<H<kf:AS2ZYDGaE`?^HZY_D]cRO[lNjd4;""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#NC>J^E3;VJ`nKSjVbJ_Il^^@0Xof9CFA2I1I^9c>""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#TfjQOCnAhM8[T3JUbLlQMS=`F=?:FPT3=X0Q]aj:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#H_6fHA8OKO><TYDXiIg[Qed<=71KC>^6cTMOjT]d""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#jN>cSCF0?I<1RSQ^g^HnBABPhUc>5Y`ahlY9HS]5""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#V;`Q_kEGIX=Mh9=UVF[Q@Q=QTT@oC]IRF]<bA1R9""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#7DKT?2VIk2^XUJ>C]G_IDe?299DJTD>1RO18Ql>F""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#U`^]IeJC;o^90V=5<ToV<Gj26hnZLolffohc8iZX""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9S?>A?E>gBl_dC[iCiiNnW7<BP;eGHf>8ceTGZ6C""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#ALLhjN7]XVBBA=VcYM8iWg^FGiG[QG03dlKYnIAe""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#6<]i]EllPZf6mnAM0D1;0eP6_G1HmRSi?`1o[a_a""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#]5Tb^6:NB]>ahEoWI5U9N5beS<?da]A]fL08AelQ""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#KhPBV8=H?G^Hmaaf^n<GcoI8eC1O_0]579;MY=81""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#A8iN_OFUPIcWac0^LU1;^HaEX[_E]<8h3N:Hm_XX""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Y811aKWEJYcX6Y1aj_I]O7TXP5j_lo;71kAiB:;:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#P@ok2DgbUDeLVA:POd`B_S@2Ocg99VQBZ<LI<gd1""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9V84FSRoD9453VdERM86a6B12VeN]hNNU:]XE`W9""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Tegah0mKcWmFhaH0K0oSjKGkmH8gDEF3SBVd2H1P""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#=II;VADkVKf7JV55ca5oUjkPaWSY7`LXTlgTV4^W""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#k7XPoXNhd8P0V7@Sd5ohO>h7io3Pl[J[8g:[_da^""); if (retval) status = ""FAIL""; Console.Write(status); } }"; var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "PASS"); compVerifier.VerifyIL("Test.Switcheroo", @" { // Code size 1115 (0x45b) .maxstack 3 .locals init (string V_0, //value uint V_1) IL_0000: ldstr """" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldstr ""C#"" IL_000c: callvirt ""int string.IndexOf(string)"" IL_0011: ldc.i4.m1 IL_0012: beq.s IL_001e IL_0014: ldarg.0 IL_0015: ldc.i4.0 IL_0016: ldc.i4.2 IL_0017: callvirt ""string string.Remove(int, int)"" IL_001c: starg.s V_0 IL_001e: ldarg.0 IL_001f: call ""ComputeStringHash"" IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: ldc.i4 0xb2f29419 IL_002b: bgt.un IL_00e0 IL_0030: ldloc.1 IL_0031: ldc.i4 0x619348d8 IL_0036: bgt.un.s IL_008c IL_0038: ldloc.1 IL_0039: ldc.i4 0x36758e37 IL_003e: bgt.un.s IL_0066 IL_0040: ldloc.1 IL_0041: ldc.i4 0x144fd20d IL_0046: beq IL_02ae IL_004b: ldloc.1 IL_004c: ldc.i4 0x14ca99e2 IL_0051: beq IL_025a IL_0056: ldloc.1 IL_0057: ldc.i4 0x36758e37 IL_005c: beq IL_0206 IL_0061: br IL_0453 IL_0066: ldloc.1 IL_0067: ldc.i4 0x5398a778 IL_006c: beq IL_021b IL_0071: ldloc.1 IL_0072: ldc.i4 0x616477cf IL_0077: beq IL_01b2 IL_007c: ldloc.1 IL_007d: ldc.i4 0x619348d8 IL_0082: beq IL_02ed IL_0087: br IL_0453 IL_008c: ldloc.1 IL_008d: ldc.i4 0x78a826a8 IL_0092: bgt.un.s IL_00ba IL_0094: ldloc.1 IL_0095: ldc.i4 0x65b3e3e5 IL_009a: beq IL_02c3 IL_009f: ldloc.1 IL_00a0: ldc.i4 0x7822b5bc IL_00a5: beq IL_0284 IL_00aa: ldloc.1 IL_00ab: ldc.i4 0x78a826a8 IL_00b0: beq IL_01dc IL_00b5: br IL_0453 IL_00ba: ldloc.1 IL_00bb: ldc.i4 0x7f66da4e IL_00c0: beq IL_0356 IL_00c5: ldloc.1 IL_00c6: ldc.i4 0xb13d374d IL_00cb: beq IL_032c IL_00d0: ldloc.1 IL_00d1: ldc.i4 0xb2f29419 IL_00d6: beq IL_0302 IL_00db: br IL_0453 IL_00e0: ldloc.1 IL_00e1: ldc.i4 0xd59864f4 IL_00e6: bgt.un.s IL_013c IL_00e8: ldloc.1 IL_00e9: ldc.i4 0xbf4a9f8e IL_00ee: bgt.un.s IL_0116 IL_00f0: ldloc.1 IL_00f1: ldc.i4 0xb6e02d3a IL_00f6: beq IL_0299 IL_00fb: ldloc.1 IL_00fc: ldc.i4 0xbaed3db3 IL_0101: beq IL_0317 IL_0106: ldloc.1 IL_0107: ldc.i4 0xbf4a9f8e IL_010c: beq IL_0230 IL_0111: br IL_0453 IL_0116: ldloc.1 IL_0117: ldc.i4 0xc6284d42 IL_011c: beq IL_01f1 IL_0121: ldloc.1 IL_0122: ldc.i4 0xd1761402 IL_0127: beq IL_01c7 IL_012c: ldloc.1 IL_012d: ldc.i4 0xd59864f4 IL_0132: beq IL_026f IL_0137: br IL_0453 IL_013c: ldloc.1 IL_013d: ldc.i4 0xeb323c73 IL_0142: bgt.un.s IL_016a IL_0144: ldloc.1 IL_0145: ldc.i4 0xdca4b248 IL_014a: beq IL_0245 IL_014f: ldloc.1 IL_0150: ldc.i4 0xe926f470 IL_0155: beq IL_036b IL_015a: ldloc.1 IL_015b: ldc.i4 0xeb323c73 IL_0160: beq IL_02d8 IL_0165: br IL_0453 IL_016a: ldloc.1 IL_016b: ldc.i4 0xf1ea0ad5 IL_0170: beq IL_0341 IL_0175: ldloc.1 IL_0176: ldc.i4 0xfa67b44d IL_017b: beq.s IL_019d IL_017d: ldloc.1 IL_017e: ldc.i4 0xfea21584 IL_0183: bne.un IL_0453 IL_0188: ldarg.0 IL_0189: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"" IL_018e: call ""bool string.op_Equality(string, string)"" IL_0193: brtrue IL_0380 IL_0198: br IL_0453 IL_019d: ldarg.0 IL_019e: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"" IL_01a3: call ""bool string.op_Equality(string, string)"" IL_01a8: brtrue IL_038b IL_01ad: br IL_0453 IL_01b2: ldarg.0 IL_01b3: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"" IL_01b8: call ""bool string.op_Equality(string, string)"" IL_01bd: brtrue IL_0396 IL_01c2: br IL_0453 IL_01c7: ldarg.0 IL_01c8: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"" IL_01cd: call ""bool string.op_Equality(string, string)"" IL_01d2: brtrue IL_03a1 IL_01d7: br IL_0453 IL_01dc: ldarg.0 IL_01dd: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"" IL_01e2: call ""bool string.op_Equality(string, string)"" IL_01e7: brtrue IL_03ac IL_01ec: br IL_0453 IL_01f1: ldarg.0 IL_01f2: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"" IL_01f7: call ""bool string.op_Equality(string, string)"" IL_01fc: brtrue IL_03b7 IL_0201: br IL_0453 IL_0206: ldarg.0 IL_0207: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"" IL_020c: call ""bool string.op_Equality(string, string)"" IL_0211: brtrue IL_03c2 IL_0216: br IL_0453 IL_021b: ldarg.0 IL_021c: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"" IL_0221: call ""bool string.op_Equality(string, string)"" IL_0226: brtrue IL_03cd IL_022b: br IL_0453 IL_0230: ldarg.0 IL_0231: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"" IL_0236: call ""bool string.op_Equality(string, string)"" IL_023b: brtrue IL_03d5 IL_0240: br IL_0453 IL_0245: ldarg.0 IL_0246: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"" IL_024b: call ""bool string.op_Equality(string, string)"" IL_0250: brtrue IL_03dd IL_0255: br IL_0453 IL_025a: ldarg.0 IL_025b: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"" IL_0260: call ""bool string.op_Equality(string, string)"" IL_0265: brtrue IL_03e5 IL_026a: br IL_0453 IL_026f: ldarg.0 IL_0270: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"" IL_0275: call ""bool string.op_Equality(string, string)"" IL_027a: brtrue IL_03ed IL_027f: br IL_0453 IL_0284: ldarg.0 IL_0285: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"" IL_028a: call ""bool string.op_Equality(string, string)"" IL_028f: brtrue IL_03f5 IL_0294: br IL_0453 IL_0299: ldarg.0 IL_029a: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"" IL_029f: call ""bool string.op_Equality(string, string)"" IL_02a4: brtrue IL_03fd IL_02a9: br IL_0453 IL_02ae: ldarg.0 IL_02af: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"" IL_02b4: call ""bool string.op_Equality(string, string)"" IL_02b9: brtrue IL_0405 IL_02be: br IL_0453 IL_02c3: ldarg.0 IL_02c4: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"" IL_02c9: call ""bool string.op_Equality(string, string)"" IL_02ce: brtrue IL_040d IL_02d3: br IL_0453 IL_02d8: ldarg.0 IL_02d9: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"" IL_02de: call ""bool string.op_Equality(string, string)"" IL_02e3: brtrue IL_0415 IL_02e8: br IL_0453 IL_02ed: ldarg.0 IL_02ee: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"" IL_02f3: call ""bool string.op_Equality(string, string)"" IL_02f8: brtrue IL_041d IL_02fd: br IL_0453 IL_0302: ldarg.0 IL_0303: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"" IL_0308: call ""bool string.op_Equality(string, string)"" IL_030d: brtrue IL_0425 IL_0312: br IL_0453 IL_0317: ldarg.0 IL_0318: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"" IL_031d: call ""bool string.op_Equality(string, string)"" IL_0322: brtrue IL_042d IL_0327: br IL_0453 IL_032c: ldarg.0 IL_032d: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"" IL_0332: call ""bool string.op_Equality(string, string)"" IL_0337: brtrue IL_0435 IL_033c: br IL_0453 IL_0341: ldarg.0 IL_0342: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"" IL_0347: call ""bool string.op_Equality(string, string)"" IL_034c: brtrue IL_043d IL_0351: br IL_0453 IL_0356: ldarg.0 IL_0357: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"" IL_035c: call ""bool string.op_Equality(string, string)"" IL_0361: brtrue IL_0445 IL_0366: br IL_0453 IL_036b: ldarg.0 IL_036c: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"" IL_0371: call ""bool string.op_Equality(string, string)"" IL_0376: brtrue IL_044d IL_037b: br IL_0453 IL_0380: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"" IL_0385: stloc.0 IL_0386: br IL_0453 IL_038b: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"" IL_0390: stloc.0 IL_0391: br IL_0453 IL_0396: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"" IL_039b: stloc.0 IL_039c: br IL_0453 IL_03a1: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"" IL_03a6: stloc.0 IL_03a7: br IL_0453 IL_03ac: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"" IL_03b1: stloc.0 IL_03b2: br IL_0453 IL_03b7: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"" IL_03bc: stloc.0 IL_03bd: br IL_0453 IL_03c2: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"" IL_03c7: stloc.0 IL_03c8: br IL_0453 IL_03cd: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"" IL_03d2: stloc.0 IL_03d3: br.s IL_0453 IL_03d5: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"" IL_03da: stloc.0 IL_03db: br.s IL_0453 IL_03dd: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"" IL_03e2: stloc.0 IL_03e3: br.s IL_0453 IL_03e5: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"" IL_03ea: stloc.0 IL_03eb: br.s IL_0453 IL_03ed: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"" IL_03f2: stloc.0 IL_03f3: br.s IL_0453 IL_03f5: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"" IL_03fa: stloc.0 IL_03fb: br.s IL_0453 IL_03fd: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"" IL_0402: stloc.0 IL_0403: br.s IL_0453 IL_0405: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"" IL_040a: stloc.0 IL_040b: br.s IL_0453 IL_040d: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"" IL_0412: stloc.0 IL_0413: br.s IL_0453 IL_0415: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"" IL_041a: stloc.0 IL_041b: br.s IL_0453 IL_041d: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"" IL_0422: stloc.0 IL_0423: br.s IL_0453 IL_0425: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"" IL_042a: stloc.0 IL_042b: br.s IL_0453 IL_042d: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"" IL_0432: stloc.0 IL_0433: br.s IL_0453 IL_0435: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"" IL_043a: stloc.0 IL_043b: br.s IL_0453 IL_043d: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"" IL_0442: stloc.0 IL_0443: br.s IL_0453 IL_0445: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"" IL_044a: stloc.0 IL_044b: br.s IL_0453 IL_044d: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"" IL_0452: stloc.0 IL_0453: ldloc.0 IL_0454: ldarg.0 IL_0455: call ""bool string.op_Equality(string, string)"" IL_045a: ret }" ); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); } [WorkItem(544322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544322")] [Fact] public void StringSwitch_HashTableSwitch_03() { var text = @" using System; class Goo { public static void Main() { Console.WriteLine(M(""blah"")); } static int M(string s) { byte[] bytes = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}; switch (s) { case ""blah"": return 1; case ""help"": return 2; case ""ooof"": return 3; case ""walk"": return 4; case ""bark"": return 5; case ""xblah"": return 1; case ""xhelp"": return 2; case ""xooof"": return 3; case ""xwalk"": return 4; case ""xbark"": return 5; case ""rblah"": return 1; case ""rhelp"": return 2; case ""rooof"": return 3; case ""rwalk"": return 4; case ""rbark"": return 5; } return bytes.Length; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); } private static void VerifySynthesizedStringHashMethod(CompilationVerifier compVerifier, bool expected) { compVerifier.VerifyMemberInIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, expected); if (expected) { compVerifier.VerifyIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, @" { // Code size 44 (0x2c) .maxstack 2 .locals init (uint V_0, int V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_002a IL_0003: ldc.i4 0x811c9dc5 IL_0008: stloc.0 IL_0009: ldc.i4.0 IL_000a: stloc.1 IL_000b: br.s IL_0021 IL_000d: ldarg.0 IL_000e: ldloc.1 IL_000f: callvirt ""char string.this[int].get"" IL_0014: ldloc.0 IL_0015: xor IL_0016: ldc.i4 0x1000193 IL_001b: mul IL_001c: stloc.0 IL_001d: ldloc.1 IL_001e: ldc.i4.1 IL_001f: add IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldarg.0 IL_0023: callvirt ""int string.Length.get"" IL_0028: blt.s IL_000d IL_002a: ldloc.0 IL_002b: ret } "); } } #endregion #region "Implicit user defined conversion tests" [WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")] [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_01() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var source = @"using System; public class Test { public static implicit operator int(Test val) { return 1; } public static implicit operator float(Test val2) { return 2.1f; } public static int Main() { Test t = new Test(); switch (t) { case 1: Console.WriteLine(0); return 0; default: Console.WriteLine(1); return 1; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"0"); } [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_02() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" class X {} class Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator X (Conv C2) { return new X(); } public static int Main() { Conv C = new Conv(); switch(C) { case 1: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_03() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" enum X { F = 0 } class Conv { // only valid operator public static implicit operator int (Conv C) { return 1; } // bool type is not valid public static implicit operator bool (Conv C2) { return false; } // enum type is not valid public static implicit operator X (Conv C3) { return X.F; } public static int Main() { Conv C = new Conv(); switch(C) { case 1: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_04() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C2) { return null; } public static int Main() { Conv? D = new Conv(); switch(D) { case 1: System.Console.WriteLine(""Fail""); return 1; case null: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_06() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C) { return null; } public static int Main() { Conv? C = new Conv(); switch(C) { case null: System.Console.WriteLine(""Pass""); return 0; case 1: System.Console.WriteLine(""Fail""); return 0; default: System.Console.WriteLine(""Fail""); return 0; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_3() { var text = @"using System; struct A { public static implicit operator int?(A? a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A a) { Console.WriteLine(""1""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "0"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_4() { var text = @"using System; struct A { public static implicit operator int?(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A? a) { Console.WriteLine(""1""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_1() { var text = @"using System; struct A { public static implicit operator int(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A? a) { Console.WriteLine(""1""); return 0; } public static implicit operator int?(A a) { Console.WriteLine(""2""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_3() { var text = @"using System; struct A { public static implicit operator int?(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int?(A? a) { Console.WriteLine(""1""); return 0; } public static implicit operator int(A a) { Console.WriteLine(""2""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } #endregion [WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")] [Fact()] public void MissingCharsProperty() { var text = @" using System; class Program { static string d = null; static void Main() { string s = ""hello""; switch (s) { case ""Hi"": d = "" Hi ""; break; case ""Bye"": d = "" Bye ""; break; case ""qwe"": d = "" qwe ""; break; case ""ert"": d = "" ert ""; break; case ""asd"": d = "" asd ""; break; case ""hello"": d = "" hello ""; break; case ""qrs"": d = "" qrs ""; break; case ""tuv"": d = "" tuv ""; break; case ""wxy"": d = "" wxy ""; break; } } } "; var comp = CreateEmptyCompilation( source: new[] { Parse(text) }, references: new[] { AacorlibRef }); var verifier = CompileAndVerify(comp, verify: Verification.Fails); verifier.VerifyIL("Program.Main", @" { // Code size 223 (0xdf) .maxstack 2 .locals init (string V_0) //s IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""Hi"" IL_000c: call ""bool string.op_Equality(string, string)"" IL_0011: brtrue.s IL_007c IL_0013: ldloc.0 IL_0014: ldstr ""Bye"" IL_0019: call ""bool string.op_Equality(string, string)"" IL_001e: brtrue.s IL_0087 IL_0020: ldloc.0 IL_0021: ldstr ""qwe"" IL_0026: call ""bool string.op_Equality(string, string)"" IL_002b: brtrue.s IL_0092 IL_002d: ldloc.0 IL_002e: ldstr ""ert"" IL_0033: call ""bool string.op_Equality(string, string)"" IL_0038: brtrue.s IL_009d IL_003a: ldloc.0 IL_003b: ldstr ""asd"" IL_0040: call ""bool string.op_Equality(string, string)"" IL_0045: brtrue.s IL_00a8 IL_0047: ldloc.0 IL_0048: ldstr ""hello"" IL_004d: call ""bool string.op_Equality(string, string)"" IL_0052: brtrue.s IL_00b3 IL_0054: ldloc.0 IL_0055: ldstr ""qrs"" IL_005a: call ""bool string.op_Equality(string, string)"" IL_005f: brtrue.s IL_00be IL_0061: ldloc.0 IL_0062: ldstr ""tuv"" IL_0067: call ""bool string.op_Equality(string, string)"" IL_006c: brtrue.s IL_00c9 IL_006e: ldloc.0 IL_006f: ldstr ""wxy"" IL_0074: call ""bool string.op_Equality(string, string)"" IL_0079: brtrue.s IL_00d4 IL_007b: ret IL_007c: ldstr "" Hi "" IL_0081: stsfld ""string Program.d"" IL_0086: ret IL_0087: ldstr "" Bye "" IL_008c: stsfld ""string Program.d"" IL_0091: ret IL_0092: ldstr "" qwe "" IL_0097: stsfld ""string Program.d"" IL_009c: ret IL_009d: ldstr "" ert "" IL_00a2: stsfld ""string Program.d"" IL_00a7: ret IL_00a8: ldstr "" asd "" IL_00ad: stsfld ""string Program.d"" IL_00b2: ret IL_00b3: ldstr "" hello "" IL_00b8: stsfld ""string Program.d"" IL_00bd: ret IL_00be: ldstr "" qrs "" IL_00c3: stsfld ""string Program.d"" IL_00c8: ret IL_00c9: ldstr "" tuv "" IL_00ce: stsfld ""string Program.d"" IL_00d3: ret IL_00d4: ldstr "" wxy "" IL_00d9: stsfld ""string Program.d"" IL_00de: ret }"); } [WorkItem(642186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642186")] [Fact()] public void IsWarningSwitchEmit() { var text = @" using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication24 { class Program { static void Main(string[] args) { TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); } private static void TimeIt() { // var sw = System.Diagnostics.Stopwatch.StartNew(); // // for (int i = 0; i < 100000000; i++) // { // IsWarning((ErrorCode)(i % 10002)); // } // // sw.Stop(); // System.Console.WriteLine(sw.ElapsedMilliseconds); } public static bool IsWarning(ErrorCode code) { switch (code) { case ErrorCode.WRN_InvalidMainSig: case ErrorCode.WRN_UnreferencedEvent: case ErrorCode.WRN_LowercaseEllSuffix: case ErrorCode.WRN_DuplicateUsing: case ErrorCode.WRN_NewRequired: case ErrorCode.WRN_NewNotRequired: case ErrorCode.WRN_NewOrOverrideExpected: case ErrorCode.WRN_UnreachableCode: case ErrorCode.WRN_UnreferencedLabel: case ErrorCode.WRN_UnreferencedVar: case ErrorCode.WRN_UnreferencedField: case ErrorCode.WRN_IsAlwaysTrue: case ErrorCode.WRN_IsAlwaysFalse: case ErrorCode.WRN_ByRefNonAgileField: case ErrorCode.WRN_OldWarning_UnsafeProp: case ErrorCode.WRN_UnreferencedVarAssg: case ErrorCode.WRN_NegativeArrayIndex: case ErrorCode.WRN_BadRefCompareLeft: case ErrorCode.WRN_BadRefCompareRight: case ErrorCode.WRN_PatternIsAmbiguous: case ErrorCode.WRN_PatternStaticOrInaccessible: case ErrorCode.WRN_PatternBadSignature: case ErrorCode.WRN_SequentialOnPartialClass: case ErrorCode.WRN_MainCantBeGeneric: case ErrorCode.WRN_UnreferencedFieldAssg: case ErrorCode.WRN_AmbiguousXMLReference: case ErrorCode.WRN_VolatileByRef: case ErrorCode.WRN_IncrSwitchObsolete: case ErrorCode.WRN_UnreachableExpr: case ErrorCode.WRN_SameFullNameThisNsAgg: case ErrorCode.WRN_SameFullNameThisAggAgg: case ErrorCode.WRN_SameFullNameThisAggNs: case ErrorCode.WRN_GlobalAliasDefn: case ErrorCode.WRN_UnexpectedPredefTypeLoc: case ErrorCode.WRN_AlwaysNull: case ErrorCode.WRN_CmpAlwaysFalse: case ErrorCode.WRN_FinalizeMethod: case ErrorCode.WRN_AmbigLookupMeth: case ErrorCode.WRN_GotoCaseShouldConvert: case ErrorCode.WRN_NubExprIsConstBool: case ErrorCode.WRN_ExplicitImplCollision: case ErrorCode.WRN_FeatureDeprecated: case ErrorCode.WRN_DeprecatedSymbol: case ErrorCode.WRN_DeprecatedSymbolStr: case ErrorCode.WRN_ExternMethodNoImplementation: case ErrorCode.WRN_ProtectedInSealed: case ErrorCode.WRN_PossibleMistakenNullStatement: case ErrorCode.WRN_UnassignedInternalField: case ErrorCode.WRN_VacuousIntegralComp: case ErrorCode.WRN_AttributeLocationOnBadDeclaration: case ErrorCode.WRN_InvalidAttributeLocation: case ErrorCode.WRN_EqualsWithoutGetHashCode: case ErrorCode.WRN_EqualityOpWithoutEquals: case ErrorCode.WRN_EqualityOpWithoutGetHashCode: case ErrorCode.WRN_IncorrectBooleanAssg: case ErrorCode.WRN_NonObsoleteOverridingObsolete: case ErrorCode.WRN_BitwiseOrSignExtend: case ErrorCode.WRN_OldWarning_ProtectedInternal: case ErrorCode.WRN_OldWarning_AccessibleReadonly: case ErrorCode.WRN_CoClassWithoutComImport: case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter: case ErrorCode.WRN_AssignmentToLockOrDispose: case ErrorCode.WRN_ObsoleteOverridingNonObsolete: case ErrorCode.WRN_DebugFullNameTooLong: case ErrorCode.WRN_ExternCtorNoImplementation: case ErrorCode.WRN_WarningDirective: case ErrorCode.WRN_UnreachableGeneralCatch: case ErrorCode.WRN_UninitializedField: case ErrorCode.WRN_DeprecatedCollectionInitAddStr: case ErrorCode.WRN_DeprecatedCollectionInitAdd: case ErrorCode.WRN_DefaultValueForUnconsumedLocation: case ErrorCode.WRN_FeatureDeprecated2: case ErrorCode.WRN_FeatureDeprecated3: case ErrorCode.WRN_FeatureDeprecated4: case ErrorCode.WRN_FeatureDeprecated5: case ErrorCode.WRN_OldWarning_FeatureDefaultDeprecated: case ErrorCode.WRN_EmptySwitch: case ErrorCode.WRN_XMLParseError: case ErrorCode.WRN_DuplicateParamTag: case ErrorCode.WRN_UnmatchedParamTag: case ErrorCode.WRN_MissingParamTag: case ErrorCode.WRN_BadXMLRef: case ErrorCode.WRN_BadXMLRefParamType: case ErrorCode.WRN_BadXMLRefReturnType: case ErrorCode.WRN_BadXMLRefSyntax: case ErrorCode.WRN_UnprocessedXMLComment: case ErrorCode.WRN_FailedInclude: case ErrorCode.WRN_InvalidInclude: case ErrorCode.WRN_MissingXMLComment: case ErrorCode.WRN_XMLParseIncludeError: case ErrorCode.WRN_OldWarning_MultipleTypeDefs: case ErrorCode.WRN_OldWarning_DocFileGenAndIncr: case ErrorCode.WRN_XMLParserNotFound: case ErrorCode.WRN_ALinkWarn: case ErrorCode.WRN_DeleteAutoResFailed: case ErrorCode.WRN_CmdOptionConflictsSource: case ErrorCode.WRN_IllegalPragma: case ErrorCode.WRN_IllegalPPWarning: case ErrorCode.WRN_BadRestoreNumber: case ErrorCode.WRN_NonECMAFeature: case ErrorCode.WRN_ErrorOverride: case ErrorCode.WRN_OldWarning_ReservedIdentifier: case ErrorCode.WRN_InvalidSearchPathDir: case ErrorCode.WRN_MissingTypeNested: case ErrorCode.WRN_MissingTypeInSource: case ErrorCode.WRN_MissingTypeInAssembly: case ErrorCode.WRN_MultiplePredefTypes: case ErrorCode.WRN_TooManyLinesForDebugger: case ErrorCode.WRN_CallOnNonAgileField: case ErrorCode.WRN_BadWarningNumber: case ErrorCode.WRN_InvalidNumber: case ErrorCode.WRN_FileNameTooLong: case ErrorCode.WRN_IllegalPPChecksum: case ErrorCode.WRN_EndOfPPLineExpected: case ErrorCode.WRN_ConflictingChecksum: case ErrorCode.WRN_AssumedMatchThis: case ErrorCode.WRN_UseSwitchInsteadOfAttribute: case ErrorCode.WRN_InvalidAssemblyName: case ErrorCode.WRN_UnifyReferenceMajMin: case ErrorCode.WRN_UnifyReferenceBldRev: case ErrorCode.WRN_DelegateNewMethBind: case ErrorCode.WRN_EmptyFileName: case ErrorCode.WRN_DuplicateTypeParamTag: case ErrorCode.WRN_UnmatchedTypeParamTag: case ErrorCode.WRN_MissingTypeParamTag: case ErrorCode.WRN_AssignmentToSelf: case ErrorCode.WRN_ComparisonToSelf: case ErrorCode.WRN_DotOnDefault: case ErrorCode.WRN_BadXMLRefTypeVar: case ErrorCode.WRN_UnmatchedParamRefTag: case ErrorCode.WRN_UnmatchedTypeParamRefTag: case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA: case ErrorCode.WRN_TypeNotFoundForNoPIAWarning: case ErrorCode.WRN_CantHaveManifestForModule: case ErrorCode.WRN_MultipleRuntimeImplementationMatches: case ErrorCode.WRN_MultipleRuntimeOverrideMatches: case ErrorCode.WRN_DynamicDispatchToConditionalMethod: case ErrorCode.WRN_IsDynamicIsConfusing: case ErrorCode.WRN_AsyncLacksAwaits: case ErrorCode.WRN_FileAlreadyIncluded: case ErrorCode.WRN_NoSources: case ErrorCode.WRN_UseNewSwitch: case ErrorCode.WRN_NoConfigNotOnCommandLine: case ErrorCode.WRN_DefineIdentifierRequired: case ErrorCode.WRN_BadUILang: case ErrorCode.WRN_CLS_NoVarArgs: case ErrorCode.WRN_CLS_BadArgType: case ErrorCode.WRN_CLS_BadReturnType: case ErrorCode.WRN_CLS_BadFieldPropType: case ErrorCode.WRN_CLS_BadUnicode: case ErrorCode.WRN_CLS_BadIdentifierCase: case ErrorCode.WRN_CLS_OverloadRefOut: case ErrorCode.WRN_CLS_OverloadUnnamed: case ErrorCode.WRN_CLS_BadIdentifier: case ErrorCode.WRN_CLS_BadBase: case ErrorCode.WRN_CLS_BadInterfaceMember: case ErrorCode.WRN_CLS_NoAbstractMembers: case ErrorCode.WRN_CLS_NotOnModules: case ErrorCode.WRN_CLS_ModuleMissingCLS: case ErrorCode.WRN_CLS_AssemblyNotCLS: case ErrorCode.WRN_CLS_BadAttributeType: case ErrorCode.WRN_CLS_ArrayArgumentToAttribute: case ErrorCode.WRN_CLS_NotOnModules2: case ErrorCode.WRN_CLS_IllegalTrueInFalse: case ErrorCode.WRN_CLS_MeaninglessOnPrivateType: case ErrorCode.WRN_CLS_AssemblyNotCLS2: case ErrorCode.WRN_CLS_MeaninglessOnParam: case ErrorCode.WRN_CLS_MeaninglessOnReturn: case ErrorCode.WRN_CLS_BadTypeVar: case ErrorCode.WRN_CLS_VolatileField: case ErrorCode.WRN_CLS_BadInterface: case ErrorCode.WRN_UnobservedAwaitableExpression: case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation: case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation: case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation: case ErrorCode.WRN_UnknownOption: case ErrorCode.WRN_MetadataNameTooLong: case ErrorCode.WRN_MainIgnored: case ErrorCode.WRN_DelaySignButNoKey: case ErrorCode.WRN_InvalidVersionFormat: case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName: case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName: case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath: case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden: case ErrorCode.WRN_UnimplementedCommandLineSwitch: case ErrorCode.WRN_RefCultureMismatch: case ErrorCode.WRN_ConflictingMachineAssembly: case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope1: case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope2: case ErrorCode.WRN_CA2202_DoNotDisposeObjectsMultipleTimes: return true; default: return false; } } internal enum ErrorCode { Void = InternalErrorCode.Void, Unknown = InternalErrorCode.Unknown, FTL_InternalError = 1, //FTL_FailedToLoadResource = 2, //FTL_NoMemory = 3, //ERR_WarningAsError = 4, //ERR_MissingOptionArg = 5, ERR_NoMetadataFile = 6, //FTL_ComPlusInit = 7, FTL_MetadataImportFailure = 8, FTL_MetadataCantOpenFile = 9, //ERR_FatalError = 10, //ERR_CantImportBase = 11, ERR_NoTypeDef = 12, FTL_MetadataEmitFailure = 13, //FTL_RequiredFileNotFound = 14, ERR_ClassNameTooLong = 15, ERR_OutputWriteFailed = 16, ERR_MultipleEntryPoints = 17, //ERR_UnimplementedOp = 18, ERR_BadBinaryOps = 19, ERR_IntDivByZero = 20, ERR_BadIndexLHS = 21, ERR_BadIndexCount = 22, ERR_BadUnaryOp = 23, //ERR_NoStdLib = 25, not used in Roslyn ERR_ThisInStaticMeth = 26, ERR_ThisInBadContext = 27, WRN_InvalidMainSig = 28, ERR_NoImplicitConv = 29, ERR_NoExplicitConv = 30, ERR_ConstOutOfRange = 31, ERR_AmbigBinaryOps = 34, ERR_AmbigUnaryOp = 35, ERR_InAttrOnOutParam = 36, ERR_ValueCantBeNull = 37, //ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired ""An object reference is required for the non-static..."" ERR_NoExplicitBuiltinConv = 39, //FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. FTL_DebugEmitFailure = 41, //FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info. //FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. ERR_BadVisReturnType = 50, ERR_BadVisParamType = 51, ERR_BadVisFieldType = 52, ERR_BadVisPropertyType = 53, ERR_BadVisIndexerReturn = 54, ERR_BadVisIndexerParam = 55, ERR_BadVisOpReturn = 56, ERR_BadVisOpParam = 57, ERR_BadVisDelegateReturn = 58, ERR_BadVisDelegateParam = 59, ERR_BadVisBaseClass = 60, ERR_BadVisBaseInterface = 61, ERR_EventNeedsBothAccessors = 65, ERR_EventNotDelegate = 66, WRN_UnreferencedEvent = 67, ERR_InterfaceEventInitializer = 68, ERR_EventPropertyInInterface = 69, ERR_BadEventUsage = 70, ERR_ExplicitEventFieldImpl = 71, ERR_CantOverrideNonEvent = 72, ERR_AddRemoveMustHaveBody = 73, ERR_AbstractEventInitializer = 74, ERR_PossibleBadNegCast = 75, ERR_ReservedEnumerator = 76, ERR_AsMustHaveReferenceType = 77, WRN_LowercaseEllSuffix = 78, ERR_BadEventUsageNoField = 79, ERR_ConstraintOnlyAllowedOnGenericDecl = 80, ERR_TypeParamMustBeIdentifier = 81, ERR_MemberReserved = 82, ERR_DuplicateParamName = 100, ERR_DuplicateNameInNS = 101, ERR_DuplicateNameInClass = 102, ERR_NameNotInContext = 103, ERR_AmbigContext = 104, WRN_DuplicateUsing = 105, ERR_BadMemberFlag = 106, ERR_BadMemberProtection = 107, WRN_NewRequired = 108, WRN_NewNotRequired = 109, ERR_CircConstValue = 110, ERR_MemberAlreadyExists = 111, ERR_StaticNotVirtual = 112, ERR_OverrideNotNew = 113, WRN_NewOrOverrideExpected = 114, ERR_OverrideNotExpected = 115, ERR_NamespaceUnexpected = 116, ERR_NoSuchMember = 117, ERR_BadSKknown = 118, ERR_BadSKunknown = 119, ERR_ObjectRequired = 120, ERR_AmbigCall = 121, ERR_BadAccess = 122, ERR_MethDelegateMismatch = 123, ERR_RetObjectRequired = 126, ERR_RetNoObjectRequired = 127, ERR_LocalDuplicate = 128, ERR_AssgLvalueExpected = 131, ERR_StaticConstParam = 132, ERR_NotConstantExpression = 133, ERR_NotNullConstRefField = 134, ERR_NameIllegallyOverrides = 135, ERR_LocalIllegallyOverrides = 136, ERR_BadUsingNamespace = 138, ERR_NoBreakOrCont = 139, ERR_DuplicateLabel = 140, ERR_NoConstructors = 143, ERR_NoNewAbstract = 144, ERR_ConstValueRequired = 145, ERR_CircularBase = 146, ERR_BadDelegateConstructor = 148, ERR_MethodNameExpected = 149, ERR_ConstantExpected = 150, // ERR_SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler. // However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future // we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used. ERR_SwitchGoverningTypeValueExpected = 151, ERR_DuplicateCaseLabel = 152, ERR_InvalidGotoCase = 153, ERR_PropertyLacksGet = 154, ERR_BadExceptionType = 155, ERR_BadEmptyThrow = 156, ERR_BadFinallyLeave = 157, ERR_LabelShadow = 158, ERR_LabelNotFound = 159, ERR_UnreachableCatch = 160, ERR_ReturnExpected = 161, WRN_UnreachableCode = 162, ERR_SwitchFallThrough = 163, WRN_UnreferencedLabel = 164, ERR_UseDefViolation = 165, //ERR_NoInvoke = 167, WRN_UnreferencedVar = 168, WRN_UnreferencedField = 169, ERR_UseDefViolationField = 170, ERR_UnassignedThis = 171, ERR_AmbigQM = 172, ERR_InvalidQM = 173, ERR_NoBaseClass = 174, ERR_BaseIllegal = 175, ERR_ObjectProhibited = 176, ERR_ParamUnassigned = 177, ERR_InvalidArray = 178, ERR_ExternHasBody = 179, ERR_AbstractAndExtern = 180, ERR_BadAttributeParamType = 181, ERR_BadAttributeArgument = 182, WRN_IsAlwaysTrue = 183, WRN_IsAlwaysFalse = 184, ERR_LockNeedsReference = 185, ERR_NullNotValid = 186, ERR_UseDefViolationThis = 188, ERR_ArgsInvalid = 190, ERR_AssgReadonly = 191, ERR_RefReadonly = 192, ERR_PtrExpected = 193, ERR_PtrIndexSingle = 196, WRN_ByRefNonAgileField = 197, ERR_AssgReadonlyStatic = 198, ERR_RefReadonlyStatic = 199, ERR_AssgReadonlyProp = 200, ERR_IllegalStatement = 201, ERR_BadGetEnumerator = 202, ERR_TooManyLocals = 204, ERR_AbstractBaseCall = 205, ERR_RefProperty = 206, WRN_OldWarning_UnsafeProp = 207, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:207"" is specified on the command line. ERR_ManagedAddr = 208, ERR_BadFixedInitType = 209, ERR_FixedMustInit = 210, ERR_InvalidAddrOp = 211, ERR_FixedNeeded = 212, ERR_FixedNotNeeded = 213, ERR_UnsafeNeeded = 214, ERR_OpTFRetType = 215, ERR_OperatorNeedsMatch = 216, ERR_BadBoolOp = 217, ERR_MustHaveOpTF = 218, WRN_UnreferencedVarAssg = 219, ERR_CheckedOverflow = 220, ERR_ConstOutOfRangeChecked = 221, ERR_BadVarargs = 224, ERR_ParamsMustBeArray = 225, ERR_IllegalArglist = 226, ERR_IllegalUnsafe = 227, //ERR_NoAccessibleMember = 228, ERR_AmbigMember = 229, ERR_BadForeachDecl = 230, ERR_ParamsLast = 231, ERR_SizeofUnsafe = 233, ERR_DottedTypeNameNotFoundInNS = 234, ERR_FieldInitRefNonstatic = 236, ERR_SealedNonOverride = 238, ERR_CantOverrideSealed = 239, //ERR_NoDefaultArgs = 241, ERR_VoidError = 242, ERR_ConditionalOnOverride = 243, ERR_PointerInAsOrIs = 244, ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated ERR_SingleTypeNameNotFound = 246, ERR_NegativeStackAllocSize = 247, ERR_NegativeArraySize = 248, ERR_OverrideFinalizeDeprecated = 249, ERR_CallingBaseFinalizeDeprecated = 250, WRN_NegativeArrayIndex = 251, WRN_BadRefCompareLeft = 252, WRN_BadRefCompareRight = 253, ERR_BadCastInFixed = 254, ERR_StackallocInCatchFinally = 255, ERR_VarargsLast = 257, ERR_MissingPartial = 260, ERR_PartialTypeKindConflict = 261, ERR_PartialModifierConflict = 262, ERR_PartialMultipleBases = 263, ERR_PartialWrongTypeParams = 264, ERR_PartialWrongConstraints = 265, ERR_NoImplicitConvCast = 266, ERR_PartialMisplaced = 267, ERR_ImportedCircularBase = 268, ERR_UseDefViolationOut = 269, ERR_ArraySizeInDeclaration = 270, ERR_InaccessibleGetter = 271, ERR_InaccessibleSetter = 272, ERR_InvalidPropertyAccessMod = 273, ERR_DuplicatePropertyAccessMods = 274, ERR_PropertyAccessModInInterface = 275, ERR_AccessModMissingAccessor = 276, ERR_UnimplementedInterfaceAccessor = 277, WRN_PatternIsAmbiguous = 278, WRN_PatternStaticOrInaccessible = 279, WRN_PatternBadSignature = 280, ERR_FriendRefNotEqualToThis = 281, WRN_SequentialOnPartialClass = 282, ERR_BadConstType = 283, ERR_NoNewTyvar = 304, ERR_BadArity = 305, ERR_BadTypeArgument = 306, ERR_TypeArgsNotAllowed = 307, ERR_HasNoTypeVars = 308, ERR_NewConstraintNotSatisfied = 310, ERR_GenericConstraintNotSatisfiedRefType = 311, ERR_GenericConstraintNotSatisfiedNullableEnum = 312, ERR_GenericConstraintNotSatisfiedNullableInterface = 313, ERR_GenericConstraintNotSatisfiedTyVar = 314, ERR_GenericConstraintNotSatisfiedValType = 315, ERR_DuplicateGeneratedName = 316, ERR_GlobalSingleTypeNameNotFound = 400, ERR_NewBoundMustBeLast = 401, WRN_MainCantBeGeneric = 402, ERR_TypeVarCantBeNull = 403, ERR_AttributeCantBeGeneric = 404, ERR_DuplicateBound = 405, ERR_ClassBoundNotFirst = 406, ERR_BadRetType = 407, ERR_DuplicateConstraintClause = 409, //ERR_WrongSignature = 410, unused in Roslyn ERR_CantInferMethTypeArgs = 411, ERR_LocalSameNameAsTypeParam = 412, ERR_AsWithTypeVar = 413, WRN_UnreferencedFieldAssg = 414, ERR_BadIndexerNameAttr = 415, ERR_AttrArgWithTypeVars = 416, ERR_NewTyvarWithArgs = 417, ERR_AbstractSealedStatic = 418, WRN_AmbiguousXMLReference = 419, WRN_VolatileByRef = 420, WRN_IncrSwitchObsolete = 422, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_ComImportWithImpl = 423, ERR_ComImportWithBase = 424, ERR_ImplBadConstraints = 425, ERR_DottedTypeNameNotFoundInAgg = 426, ERR_MethGrpToNonDel = 428, WRN_UnreachableExpr = 429, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_BadExternAlias = 430, ERR_ColColWithTypeAlias = 431, ERR_AliasNotFound = 432, ERR_SameFullNameAggAgg = 433, ERR_SameFullNameNsAgg = 434, WRN_SameFullNameThisNsAgg = 435, WRN_SameFullNameThisAggAgg = 436, WRN_SameFullNameThisAggNs = 437, ERR_SameFullNameThisAggThisNs = 438, ERR_ExternAfterElements = 439, WRN_GlobalAliasDefn = 440, ERR_SealedStaticClass = 441, ERR_PrivateAbstractAccessor = 442, ERR_ValueExpected = 443, WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_UnboxNotLValue = 445, ERR_AnonMethGrpInForEach = 446, //ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error. ERR_BadIncDecRetType = 448, ERR_TypeConstraintsMustBeUniqueAndFirst = 449, ERR_RefValBoundWithClass = 450, ERR_NewBoundWithVal = 451, ERR_RefConstraintNotSatisfied = 452, ERR_ValConstraintNotSatisfied = 453, ERR_CircularConstraint = 454, ERR_BaseConstraintConflict = 455, ERR_ConWithValCon = 456, ERR_AmbigUDConv = 457, WRN_AlwaysNull = 458, ERR_AddrOnReadOnlyLocal = 459, ERR_OverrideWithConstraints = 460, ERR_AmbigOverride = 462, ERR_DecConstError = 463, WRN_CmpAlwaysFalse = 464, WRN_FinalizeMethod = 465, ERR_ExplicitImplParams = 466, WRN_AmbigLookupMeth = 467, ERR_SameFullNameThisAggThisAgg = 468, WRN_GotoCaseShouldConvert = 469, ERR_MethodImplementingAccessor = 470, //ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn WRN_NubExprIsConstBool = 472, WRN_ExplicitImplCollision = 473, ERR_AbstractHasBody = 500, ERR_ConcreteMissingBody = 501, ERR_AbstractAndSealed = 502, ERR_AbstractNotVirtual = 503, ERR_StaticConstant = 504, ERR_CantOverrideNonFunction = 505, ERR_CantOverrideNonVirtual = 506, ERR_CantChangeAccessOnOverride = 507, ERR_CantChangeReturnTypeOnOverride = 508, ERR_CantDeriveFromSealedType = 509, ERR_AbstractInConcreteClass = 513, ERR_StaticConstructorWithExplicitConstructorCall = 514, ERR_StaticConstructorWithAccessModifiers = 515, ERR_RecursiveConstructorCall = 516, ERR_ObjectCallingBaseConstructor = 517, ERR_PredefinedTypeNotFound = 518, //ERR_PredefinedTypeBadType = 520, ERR_StructWithBaseConstructorCall = 522, ERR_StructLayoutCycle = 523, ERR_InterfacesCannotContainTypes = 524, ERR_InterfacesCantContainFields = 525, ERR_InterfacesCantContainConstructors = 526, ERR_NonInterfaceInInterfaceList = 527, ERR_DuplicateInterfaceInBaseList = 528, ERR_CycleInInterfaceInheritance = 529, ERR_InterfaceMemberHasBody = 531, ERR_HidingAbstractMethod = 533, ERR_UnimplementedAbstractMethod = 534, ERR_UnimplementedInterfaceMember = 535, ERR_ObjectCantHaveBases = 537, ERR_ExplicitInterfaceImplementationNotInterface = 538, ERR_InterfaceMemberNotFound = 539, ERR_ClassDoesntImplementInterface = 540, ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541, ERR_MemberNameSameAsType = 542, ERR_EnumeratorOverflow = 543, ERR_CantOverrideNonProperty = 544, ERR_NoGetToOverride = 545, ERR_NoSetToOverride = 546, ERR_PropertyCantHaveVoidType = 547, ERR_PropertyWithNoAccessors = 548, ERR_NewVirtualInSealed = 549, ERR_ExplicitPropertyAddingAccessor = 550, ERR_ExplicitPropertyMissingAccessor = 551, ERR_ConversionWithInterface = 552, ERR_ConversionWithBase = 553, ERR_ConversionWithDerived = 554, ERR_IdentityConversion = 555, ERR_ConversionNotInvolvingContainedType = 556, ERR_DuplicateConversionInClass = 557, ERR_OperatorsMustBeStatic = 558, ERR_BadIncDecSignature = 559, ERR_BadUnaryOperatorSignature = 562, ERR_BadBinaryOperatorSignature = 563, ERR_BadShiftOperatorSignature = 564, ERR_InterfacesCantContainOperators = 567, ERR_StructsCantContainDefaultConstructor = 568, ERR_CantOverrideBogusMethod = 569, ERR_BindToBogus = 570, ERR_CantCallSpecialMethod = 571, ERR_BadTypeReference = 572, ERR_FieldInitializerInStruct = 573, ERR_BadDestructorName = 574, ERR_OnlyClassesCanContainDestructors = 575, ERR_ConflictAliasAndMember = 576, ERR_ConditionalOnSpecialMethod = 577, ERR_ConditionalMustReturnVoid = 578, ERR_DuplicateAttribute = 579, ERR_ConditionalOnInterfaceMethod = 582, //ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused //ERR_ICE_Symbol = 584, //ERR_ICE_Node = 585, //ERR_ICE_File = 586, //ERR_ICE_Stage = 587, //ERR_ICE_Lexer = 588, //ERR_ICE_Parser = 589, ERR_OperatorCantReturnVoid = 590, ERR_InvalidAttributeArgument = 591, ERR_AttributeOnBadSymbolType = 592, ERR_FloatOverflow = 594, ERR_ComImportWithoutUuidAttribute = 596, ERR_InvalidNamedArgument = 599, ERR_DllImportOnInvalidMethod = 601, WRN_FeatureDeprecated = 602, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:602"" is specified on the command line. // ERR_NameAttributeOnOverride = 609, // removed in Roslyn ERR_FieldCantBeRefAny = 610, ERR_ArrayElementCantBeRefAny = 611, WRN_DeprecatedSymbol = 612, ERR_NotAnAttributeClass = 616, ERR_BadNamedAttributeArgument = 617, WRN_DeprecatedSymbolStr = 618, ERR_DeprecatedSymbolStr = 619, ERR_IndexerCantHaveVoidType = 620, ERR_VirtualPrivate = 621, ERR_ArrayInitToNonArrayType = 622, ERR_ArrayInitInBadPlace = 623, ERR_MissingStructOffset = 625, WRN_ExternMethodNoImplementation = 626, WRN_ProtectedInSealed = 628, ERR_InterfaceImplementedByConditional = 629, ERR_IllegalRefParam = 631, ERR_BadArgumentToAttribute = 633, //ERR_MissingComTypeOrMarshaller = 635, ERR_StructOffsetOnBadStruct = 636, ERR_StructOffsetOnBadField = 637, ERR_AttributeUsageOnNonAttributeClass = 641, WRN_PossibleMistakenNullStatement = 642, ERR_DuplicateNamedAttributeArgument = 643, ERR_DeriveFromEnumOrValueType = 644, ERR_DefaultMemberOnIndexedType = 646, //ERR_CustomAttributeError = 647, ERR_BogusType = 648, WRN_UnassignedInternalField = 649, ERR_CStyleArray = 650, WRN_VacuousIntegralComp = 652, ERR_AbstractAttributeClass = 653, ERR_BadNamedAttributeArgumentType = 655, ERR_MissingPredefinedMember = 656, WRN_AttributeLocationOnBadDeclaration = 657, WRN_InvalidAttributeLocation = 658, WRN_EqualsWithoutGetHashCode = 659, WRN_EqualityOpWithoutEquals = 660, WRN_EqualityOpWithoutGetHashCode = 661, ERR_OutAttrOnRefParam = 662, ERR_OverloadRefKind = 663, ERR_LiteralDoubleCast = 664, WRN_IncorrectBooleanAssg = 665, ERR_ProtectedInStruct = 666, //ERR_FeatureDeprecated = 667, ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler ERR_ComImportWithUserCtor = 669, ERR_FieldCantHaveVoidType = 670, WRN_NonObsoleteOverridingObsolete = 672, ERR_SystemVoid = 673, ERR_ExplicitParamArray = 674, WRN_BitwiseOrSignExtend = 675, ERR_VolatileStruct = 677, ERR_VolatileAndReadonly = 678, WRN_OldWarning_ProtectedInternal = 679, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:679"" is specified on the command line. WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:680"" is specified on the command line. ERR_AbstractField = 681, ERR_BogusExplicitImpl = 682, ERR_ExplicitMethodImplAccessor = 683, WRN_CoClassWithoutComImport = 684, ERR_ConditionalWithOutParam = 685, ERR_AccessorImplementingMethod = 686, ERR_AliasQualAsExpression = 687, ERR_DerivingFromATyVar = 689, //FTL_MalformedMetadata = 690, ERR_DuplicateTypeParameter = 692, WRN_TypeParameterSameAsOuterTypeParameter = 693, ERR_TypeVariableSameAsParent = 694, ERR_UnifyingInterfaceInstantiations = 695, ERR_GenericDerivingFromAttribute = 698, ERR_TyVarNotFoundInConstraint = 699, ERR_BadBoundType = 701, ERR_SpecialTypeAsBound = 702, ERR_BadVisBound = 703, ERR_LookupInTypeVariable = 704, ERR_BadConstraintType = 706, ERR_InstanceMemberInStaticClass = 708, ERR_StaticBaseClass = 709, ERR_ConstructorInStaticClass = 710, ERR_DestructorInStaticClass = 711, ERR_InstantiatingStaticClass = 712, ERR_StaticDerivedFromNonObject = 713, ERR_StaticClassInterfaceImpl = 714, ERR_OperatorInStaticClass = 715, ERR_ConvertToStaticClass = 716, ERR_ConstraintIsStaticClass = 717, ERR_GenericArgIsStaticClass = 718, ERR_ArrayOfStaticClass = 719, ERR_IndexerInStaticClass = 720, ERR_ParameterIsStaticClass = 721, ERR_ReturnTypeIsStaticClass = 722, ERR_VarDeclIsStaticClass = 723, ERR_BadEmptyThrowInFinally = 724, //ERR_InvalidDecl = 725, //ERR_InvalidSpecifier = 726, //ERR_InvalidSpecifierUnk = 727, WRN_AssignmentToLockOrDispose = 728, ERR_ForwardedTypeInThisAssembly = 729, ERR_ForwardedTypeIsNested = 730, ERR_CycleInTypeForwarder = 731, //ERR_FwdedGeneric = 733, ERR_AssemblyNameOnNonModule = 734, ERR_InvalidFwdType = 735, ERR_CloseUnimplementedInterfaceMemberStatic = 736, ERR_CloseUnimplementedInterfaceMemberNotPublic = 737, ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738, ERR_DuplicateTypeForwarder = 739, ERR_ExpectedSelectOrGroup = 742, ERR_ExpectedContextualKeywordOn = 743, ERR_ExpectedContextualKeywordEquals = 744, ERR_ExpectedContextualKeywordBy = 745, ERR_InvalidAnonymousTypeMemberDeclarator = 746, ERR_InvalidInitializerElementInitializer = 747, ERR_InconsistentLambdaParameterUsage = 748, ERR_PartialMethodInvalidModifier = 750, ERR_PartialMethodOnlyInPartialClass = 751, ERR_PartialMethodCannotHaveOutParameters = 752, ERR_PartialMethodOnlyMethods = 753, ERR_PartialMethodNotExplicit = 754, ERR_PartialMethodExtensionDifference = 755, ERR_PartialMethodOnlyOneLatent = 756, ERR_PartialMethodOnlyOneActual = 757, ERR_PartialMethodParamsDifference = 758, ERR_PartialMethodMustHaveLatent = 759, ERR_PartialMethodInconsistentConstraints = 761, ERR_PartialMethodToDelegate = 762, ERR_PartialMethodStaticDifference = 763, ERR_PartialMethodUnsafeDifference = 764, ERR_PartialMethodInExpressionTree = 765, ERR_PartialMethodMustReturnVoid = 766, ERR_ExplicitImplCollisionOnRefOut = 767, //ERR_NoEmptyArrayRanges = 800, //ERR_IntegerSpecifierOnOneDimArrays = 801, //ERR_IntegerSpecifierMustBePositive = 802, //ERR_ArrayRangeDimensionsMustMatch = 803, //ERR_ArrayRangeDimensionsWrong = 804, //ERR_IntegerSpecifierValidOnlyOnArrays = 805, //ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806, //ERR_UseAdditionalSquareBrackets = 807, //ERR_DotDotNotAssociative = 808, WRN_ObsoleteOverridingNonObsolete = 809, WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer ERR_ImplicitlyTypedLocalCannotBeFixed = 821, ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst WRN_ExternCtorNoImplementation = 824, ERR_TypeVarNotFound = 825, ERR_ImplicitlyTypedArrayNoBestType = 826, ERR_AnonymousTypePropertyAssignedBadValue = 828, ERR_ExpressionTreeContainsBaseAccess = 831, ERR_ExpressionTreeContainsAssignment = 832, ERR_AnonymousTypeDuplicatePropertyName = 833, ERR_StatementLambdaToExpressionTree = 834, ERR_ExpressionTreeMustHaveDelegate = 835, ERR_AnonymousTypeNotAvailable = 836, ERR_LambdaInIsAs = 837, ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838, ERR_MissingArgument = 839, ERR_AutoPropertiesMustHaveBothAccessors = 840, ERR_VariableUsedBeforeDeclaration = 841, ERR_ExplicitLayoutAndAutoImplementedProperty = 842, ERR_UnassignedThisAutoProperty = 843, ERR_VariableUsedBeforeDeclarationAndHidesField = 844, ERR_ExpressionTreeContainsBadCoalesce = 845, ERR_ArrayInitializerExpected = 846, ERR_ArrayInitializerIncorrectLength = 847, // ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind ERR_ExpressionTreeContainsNamedArgument = 853, ERR_ExpressionTreeContainsOptionalArgument = 854, ERR_ExpressionTreeContainsIndexedProperty = 855, ERR_IndexedPropertyRequiresParams = 856, ERR_IndexedPropertyMustHaveAllOptionalParams = 857, ERR_FusionConfigFileNameTooLong = 858, ERR_IdentifierExpected = 1001, ERR_SemicolonExpected = 1002, ERR_SyntaxError = 1003, ERR_DuplicateModifier = 1004, ERR_DuplicateAccessor = 1007, ERR_IntegralTypeExpected = 1008, ERR_IllegalEscape = 1009, ERR_NewlineInConst = 1010, ERR_EmptyCharConst = 1011, ERR_TooManyCharsInConst = 1012, ERR_InvalidNumber = 1013, ERR_GetOrSetExpected = 1014, ERR_ClassTypeExpected = 1015, ERR_NamedArgumentExpected = 1016, ERR_TooManyCatches = 1017, ERR_ThisOrBaseExpected = 1018, ERR_OvlUnaryOperatorExpected = 1019, ERR_OvlBinaryOperatorExpected = 1020, ERR_IntOverflow = 1021, ERR_EOFExpected = 1022, ERR_BadEmbeddedStmt = 1023, ERR_PPDirectiveExpected = 1024, ERR_EndOfPPLineExpected = 1025, ERR_CloseParenExpected = 1026, ERR_EndifDirectiveExpected = 1027, ERR_UnexpectedDirective = 1028, ERR_ErrorDirective = 1029, WRN_WarningDirective = 1030, ERR_TypeExpected = 1031, ERR_PPDefFollowsToken = 1032, //ERR_TooManyLines = 1033, unused in Roslyn. //ERR_LineTooLong = 1034, unused in Roslyn. ERR_OpenEndedComment = 1035, ERR_OvlOperatorExpected = 1037, ERR_EndRegionDirectiveExpected = 1038, ERR_UnterminatedStringLit = 1039, ERR_BadDirectivePlacement = 1040, ERR_IdentifierExpectedKW = 1041, ERR_SemiOrLBraceExpected = 1043, ERR_MultiTypeInDeclaration = 1044, ERR_AddOrRemoveExpected = 1055, ERR_UnexpectedCharacter = 1056, ERR_ProtectedInStatic = 1057, WRN_UnreachableGeneralCatch = 1058, ERR_IncrementLvalueExpected = 1059, WRN_UninitializedField = 1060, //unused in Roslyn but preserving for the purposes of not breaking users' /nowarn settings ERR_NoSuchMemberOrExtension = 1061, WRN_DeprecatedCollectionInitAddStr = 1062, ERR_DeprecatedCollectionInitAddStr = 1063, WRN_DeprecatedCollectionInitAdd = 1064, ERR_DefaultValueNotAllowed = 1065, WRN_DefaultValueForUnconsumedLocation = 1066, ERR_PartialWrongTypeParamsVariance = 1067, ERR_GlobalSingleTypeNameNotFoundFwd = 1068, ERR_DottedTypeNameNotFoundInNSFwd = 1069, ERR_SingleTypeNameNotFoundFwd = 1070, //ERR_NoSuchMemberOnNoPIAType = 1071, //EE // ERR_EOLExpected = 1099, // EE // ERR_NotSupportedinEE = 1100, // EE ERR_BadThisParam = 1100, ERR_BadRefWithThis = 1101, ERR_BadOutWithThis = 1102, ERR_BadTypeforThis = 1103, ERR_BadParamModThis = 1104, ERR_BadExtensionMeth = 1105, ERR_BadExtensionAgg = 1106, ERR_DupParamMod = 1107, ERR_MultiParamMod = 1108, ERR_ExtensionMethodsDecl = 1109, ERR_ExtensionAttrNotFound = 1110, //ERR_ExtensionTypeParam = 1111, ERR_ExplicitExtension = 1112, ERR_ValueTypeExtDelegate = 1113, // Below five error codes are unused, but we still need to retain them to suppress CS1691 when ""/nowarn:1200,1201,1202,1203,1204"" is specified on the command line. WRN_FeatureDeprecated2 = 1200, WRN_FeatureDeprecated3 = 1201, WRN_FeatureDeprecated4 = 1202, WRN_FeatureDeprecated5 = 1203, WRN_OldWarning_FeatureDefaultDeprecated = 1204, ERR_BadArgCount = 1501, //ERR_BadArgTypes = 1502, ERR_BadArgType = 1503, ERR_NoSourceFile = 1504, ERR_CantRefResource = 1507, ERR_ResourceNotUnique = 1508, ERR_ImportNonAssembly = 1509, ERR_RefLvalueExpected = 1510, ERR_BaseInStaticMeth = 1511, ERR_BaseInBadContext = 1512, ERR_RbraceExpected = 1513, ERR_LbraceExpected = 1514, ERR_InExpected = 1515, ERR_InvalidPreprocExpr = 1517, //ERR_BadTokenInType = 1518, unused in Roslyn ERR_InvalidMemberDecl = 1519, ERR_MemberNeedsType = 1520, ERR_BadBaseType = 1521, WRN_EmptySwitch = 1522, ERR_ExpectedEndTry = 1524, ERR_InvalidExprTerm = 1525, ERR_BadNewExpr = 1526, ERR_NoNamespacePrivate = 1527, ERR_BadVarDecl = 1528, ERR_UsingAfterElements = 1529, //ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this. //ERR_DontUseInvoke = 1533, ERR_BadBinOpArgs = 1534, ERR_BadUnOpArgs = 1535, ERR_NoVoidParameter = 1536, ERR_DuplicateAlias = 1537, ERR_BadProtectedAccess = 1540, //ERR_CantIncludeDirectory = 1541, ERR_AddModuleAssembly = 1542, ERR_BindToBogusProp2 = 1545, ERR_BindToBogusProp1 = 1546, ERR_NoVoidHere = 1547, //ERR_CryptoFailed = 1548, //ERR_CryptoNotFound = 1549, ERR_IndexerNeedsParam = 1551, ERR_BadArraySyntax = 1552, ERR_BadOperatorSyntax = 1553, ERR_BadOperatorSyntax2 = 1554, ERR_MainClassNotFound = 1555, ERR_MainClassNotClass = 1556, ERR_MainClassWrongFile = 1557, ERR_NoMainInClass = 1558, ERR_MainClassIsImport = 1559, //ERR_FileNameTooLong = 1560, ERR_OutputFileNameTooLong = 1561, ERR_OutputNeedsName = 1562, //ERR_OutputNeedsInput = 1563, ERR_CantHaveWin32ResAndManifest = 1564, ERR_CantHaveWin32ResAndIcon = 1565, ERR_CantReadResource = 1566, //ERR_AutoResGen = 1567, //ERR_DocFileGen = 1569, WRN_XMLParseError = 1570, WRN_DuplicateParamTag = 1571, WRN_UnmatchedParamTag = 1572, WRN_MissingParamTag = 1573, WRN_BadXMLRef = 1574, ERR_BadStackAllocExpr = 1575, ERR_InvalidLineNumber = 1576, //ERR_ALinkFailed = 1577, No alink usage in Roslyn ERR_MissingPPFile = 1578, ERR_ForEachMissingMember = 1579, WRN_BadXMLRefParamType = 1580, WRN_BadXMLRefReturnType = 1581, ERR_BadWin32Res = 1583, WRN_BadXMLRefSyntax = 1584, ERR_BadModifierLocation = 1585, ERR_MissingArraySize = 1586, WRN_UnprocessedXMLComment = 1587, //ERR_CantGetCORSystemDir = 1588, WRN_FailedInclude = 1589, WRN_InvalidInclude = 1590, WRN_MissingXMLComment = 1591, WRN_XMLParseIncludeError = 1592, ERR_BadDelArgCount = 1593, //ERR_BadDelArgTypes = 1594, WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1595"" is specified on the command line. WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1596"" is specified on the command line. ERR_UnexpectedSemicolon = 1597, WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time). ERR_MethodReturnCantBeRefAny = 1599, ERR_CompileCancelled = 1600, ERR_MethodArgCantBeRefAny = 1601, ERR_AssgReadonlyLocal = 1604, ERR_RefReadonlyLocal = 1605, //ERR_ALinkCloseFailed = 1606, WRN_ALinkWarn = 1607, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1607"" is specified on the command line. ERR_CantUseRequiredAttribute = 1608, ERR_NoModifiersOnAccessor = 1609, WRN_DeleteAutoResFailed = 1610, // Unused but preserving for /nowarn ERR_ParamsCantBeRefOut = 1611, ERR_ReturnNotLValue = 1612, ERR_MissingCoClass = 1613, ERR_AmbiguousAttribute = 1614, ERR_BadArgExtraRef = 1615, WRN_CmdOptionConflictsSource = 1616, ERR_BadCompatMode = 1617, ERR_DelegateOnConditional = 1618, //ERR_CantMakeTempFile = 1619, ERR_BadArgRef = 1620, ERR_YieldInAnonMeth = 1621, ERR_ReturnInIterator = 1622, ERR_BadIteratorArgType = 1623, ERR_BadIteratorReturn = 1624, ERR_BadYieldInFinally = 1625, ERR_BadYieldInTryOfCatch = 1626, ERR_EmptyYield = 1627, ERR_AnonDelegateCantUse = 1628, ERR_IllegalInnerUnsafe = 1629, //ERR_BadWatsonMode = 1630, ERR_BadYieldInCatch = 1631, ERR_BadDelegateLeave = 1632, WRN_IllegalPragma = 1633, WRN_IllegalPPWarning = 1634, WRN_BadRestoreNumber = 1635, ERR_VarargsIterator = 1636, ERR_UnsafeIteratorArgType = 1637, //ERR_ReservedIdentifier = 1638, ERR_BadCoClassSig = 1639, ERR_MultipleIEnumOfT = 1640, ERR_FixedDimsRequired = 1641, ERR_FixedNotInStruct = 1642, ERR_AnonymousReturnExpected = 1643, ERR_NonECMAFeature = 1644, WRN_NonECMAFeature = 1645, ERR_ExpectedVerbatimLiteral = 1646, //FTL_StackOverflow = 1647, ERR_AssgReadonly2 = 1648, ERR_RefReadonly2 = 1649, ERR_AssgReadonlyStatic2 = 1650, ERR_RefReadonlyStatic2 = 1651, ERR_AssgReadonlyLocal2Cause = 1654, ERR_RefReadonlyLocal2Cause = 1655, ERR_AssgReadonlyLocalCause = 1656, ERR_RefReadonlyLocalCause = 1657, WRN_ErrorOverride = 1658, WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1659"" is specified on the command line. ERR_AnonMethToNonDel = 1660, ERR_CantConvAnonMethParams = 1661, ERR_CantConvAnonMethReturns = 1662, ERR_IllegalFixedType = 1663, ERR_FixedOverflow = 1664, ERR_InvalidFixedArraySize = 1665, ERR_FixedBufferNotFixed = 1666, ERR_AttributeNotOnAccessor = 1667, WRN_InvalidSearchPathDir = 1668, ERR_IllegalVarArgs = 1669, ERR_IllegalParams = 1670, ERR_BadModifiersOnNamespace = 1671, ERR_BadPlatformType = 1672, ERR_ThisStructNotInAnonMeth = 1673, ERR_NoConvToIDisp = 1674, // ERR_InvalidGenericEnum = 1675, replaced with 7002 ERR_BadParamRef = 1676, ERR_BadParamExtraRef = 1677, ERR_BadParamType = 1678, ERR_BadExternIdentifier = 1679, ERR_AliasMissingFile = 1680, ERR_GlobalExternAlias = 1681, WRN_MissingTypeNested = 1682, //unused in Roslyn. // 1683 and 1684 are unused warning codes, but we still need to retain them to suppress CS1691 when ""/nowarn:1683"" is specified on the command line. // In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively. WRN_MissingTypeInSource = 1683, WRN_MissingTypeInAssembly = 1684, WRN_MultiplePredefTypes = 1685, ERR_LocalCantBeFixedAndHoisted = 1686, WRN_TooManyLinesForDebugger = 1687, ERR_CantConvAnonMethNoParams = 1688, ERR_ConditionalOnNonAttributeClass = 1689, WRN_CallOnNonAgileField = 1690, WRN_BadWarningNumber = 1691, WRN_InvalidNumber = 1692, WRN_FileNameTooLong = 1694, //unused but preserving for the sake of existing code using /nowarn:1694 WRN_IllegalPPChecksum = 1695, WRN_EndOfPPLineExpected = 1696, WRN_ConflictingChecksum = 1697, WRN_AssumedMatchThis = 1698, WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1699"" is specified. WRN_InvalidAssemblyName = 1700, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1700"" is specified. WRN_UnifyReferenceMajMin = 1701, WRN_UnifyReferenceBldRev = 1702, ERR_DuplicateImport = 1703, ERR_DuplicateImportSimple = 1704, ERR_AssemblyMatchBadVersion = 1705, ERR_AnonMethNotAllowed = 1706, WRN_DelegateNewMethBind = 1707, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1707"" is specified. ERR_FixedNeedsLvalue = 1708, WRN_EmptyFileName = 1709, WRN_DuplicateTypeParamTag = 1710, WRN_UnmatchedTypeParamTag = 1711, WRN_MissingTypeParamTag = 1712, //FTL_TypeNameBuilderError = 1713, ERR_ImportBadBase = 1714, ERR_CantChangeTypeOnOverride = 1715, ERR_DoNotUseFixedBufferAttr = 1716, WRN_AssignmentToSelf = 1717, WRN_ComparisonToSelf = 1718, ERR_CantOpenWin32Res = 1719, WRN_DotOnDefault = 1720, ERR_NoMultipleInheritance = 1721, ERR_BaseClassMustBeFirst = 1722, WRN_BadXMLRefTypeVar = 1723, //ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn. ERR_FriendAssemblyBadArgs = 1725, ERR_FriendAssemblySNReq = 1726, //ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings. ERR_DelegateOnNullable = 1728, ERR_BadCtorArgCount = 1729, ERR_GlobalAttributesNotFirst = 1730, ERR_CantConvAnonMethReturnsNoDelegate = 1731, //ERR_ParameterExpected = 1732, Not used in Roslyn. ERR_ExpressionExpected = 1733, WRN_UnmatchedParamRefTag = 1734, WRN_UnmatchedTypeParamRefTag = 1735, ERR_DefaultValueMustBeConstant = 1736, ERR_DefaultValueBeforeRequiredValue = 1737, ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738, ERR_BadNamedArgument = 1739, ERR_DuplicateNamedArgument = 1740, ERR_RefOutDefaultValue = 1741, ERR_NamedArgumentForArray = 1742, ERR_DefaultValueForExtensionParameter = 1743, ERR_NamedArgumentUsedInPositional = 1744, ERR_DefaultValueUsedWithAttributes = 1745, ERR_BadNamedArgumentForDelegateInvoke = 1746, ERR_NoPIAAssemblyMissingAttribute = 1747, ERR_NoCanonicalView = 1748, //ERR_TypeNotFoundForNoPIA = 1749, ERR_NoConversionForDefaultParam = 1750, ERR_DefaultValueForParamsParameter = 1751, ERR_NewCoClassOnLink = 1752, ERR_NoPIANestedType = 1754, //ERR_InvalidTypeIdentifierConstructor = 1755, ERR_InteropTypeMissingAttribute = 1756, ERR_InteropStructContainsMethods = 1757, ERR_InteropTypesWithSameNameAndGuid = 1758, ERR_NoPIAAssemblyMissingAttributes = 1759, ERR_AssemblySpecifiedForLinkAndRef = 1760, ERR_LocalTypeNameClash = 1761, WRN_ReferencedAssemblyReferencesLinkedPIA = 1762, ERR_NotNullRefDefaultParameter = 1763, ERR_FixedLocalInLambda = 1764, WRN_TypeNotFoundForNoPIAWarning = 1765, ERR_MissingMethodOnSourceInterface = 1766, ERR_MissingSourceInterface = 1767, ERR_GenericsUsedInNoPIAType = 1768, ERR_GenericsUsedAcrossAssemblies = 1769, ERR_NoConversionForNubDefaultParam = 1770, //ERR_MemberWithGenericsUsedAcrossAssemblies = 1771, //ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772, ERR_BadSubsystemVersion = 1773, ERR_InteropMethodWithBody = 1774, ERR_BadWarningLevel = 1900, ERR_BadDebugType = 1902, //ERR_UnknownTestSwitch = 1903, ERR_BadResourceVis = 1906, ERR_DefaultValueTypeMustMatch = 1908, //ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn. ERR_DefaultValueBadValueType = 1910, ERR_MemberAlreadyInitialized = 1912, ERR_MemberCannotBeInitialized = 1913, ERR_StaticMemberInObjectInitializer = 1914, ERR_ReadonlyValueTypeInObjectInitializer = 1917, ERR_ValueTypePropertyInObjectInitializer = 1918, ERR_UnsafeTypeInObjectCreation = 1919, ERR_EmptyElementInitializer = 1920, ERR_InitializerAddHasWrongSignature = 1921, ERR_CollectionInitRequiresIEnumerable = 1922, ERR_InvalidCollectionInitializerType = 1925, ERR_CantOpenWin32Manifest = 1926, WRN_CantHaveManifestForModule = 1927, ERR_BadExtensionArgTypes = 1928, ERR_BadInstanceArgType = 1929, ERR_QueryDuplicateRangeVariable = 1930, ERR_QueryRangeVariableOverrides = 1931, ERR_QueryRangeVariableAssignedBadValue = 1932, ERR_QueryNotAllowed = 1933, ERR_QueryNoProviderCastable = 1934, ERR_QueryNoProviderStandard = 1935, ERR_QueryNoProvider = 1936, ERR_QueryOuterKey = 1937, ERR_QueryInnerKey = 1938, ERR_QueryOutRefRangeVariable = 1939, ERR_QueryMultipleProviders = 1940, ERR_QueryTypeInferenceFailedMulti = 1941, ERR_QueryTypeInferenceFailed = 1942, ERR_QueryTypeInferenceFailedSelectMany = 1943, ERR_ExpressionTreeContainsPointerOp = 1944, ERR_ExpressionTreeContainsAnonymousMethod = 1945, ERR_AnonymousMethodToExpressionTree = 1946, ERR_QueryRangeVariableReadOnly = 1947, ERR_QueryRangeVariableSameAsTypeParam = 1948, ERR_TypeVarNotFoundRangeVariable = 1949, ERR_BadArgTypesForCollectionAdd = 1950, ERR_ByRefParameterInExpressionTree = 1951, ERR_VarArgsInExpressionTree = 1952, ERR_MemGroupInExpressionTree = 1953, ERR_InitializerAddHasParamModifiers = 1954, ERR_NonInvocableMemberCalled = 1955, WRN_MultipleRuntimeImplementationMatches = 1956, WRN_MultipleRuntimeOverrideMatches = 1957, ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958, ERR_InvalidConstantDeclarationType = 1959, ERR_IllegalVarianceSyntax = 1960, ERR_UnexpectedVariance = 1961, ERR_BadDynamicTypeof = 1962, ERR_ExpressionTreeContainsDynamicOperation = 1963, ERR_BadDynamicConversion = 1964, ERR_DeriveFromDynamic = 1965, ERR_DeriveFromConstructedDynamic = 1966, ERR_DynamicTypeAsBound = 1967, ERR_ConstructedDynamicTypeAsBound = 1968, ERR_DynamicRequiredTypesMissing = 1969, ERR_ExplicitDynamicAttr = 1970, ERR_NoDynamicPhantomOnBase = 1971, ERR_NoDynamicPhantomOnBaseIndexer = 1972, ERR_BadArgTypeDynamicExtension = 1973, WRN_DynamicDispatchToConditionalMethod = 1974, ERR_NoDynamicPhantomOnBaseCtor = 1975, ERR_BadDynamicMethodArgMemgrp = 1976, ERR_BadDynamicMethodArgLambda = 1977, ERR_BadDynamicMethodArg = 1978, ERR_BadDynamicQuery = 1979, ERR_DynamicAttributeMissing = 1980, WRN_IsDynamicIsConfusing = 1981, ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn. ERR_BadAsyncReturn = 1983, ERR_BadAwaitInFinally = 1984, ERR_BadAwaitInCatch = 1985, ERR_BadAwaitArg = 1986, ERR_BadAsyncArgType = 1988, ERR_BadAsyncExpressionTree = 1989, ERR_WindowsRuntimeTypesMissing = 1990, ERR_MixingWinRTEventWithRegular = 1991, ERR_BadAwaitWithoutAsync = 1992, ERR_MissingAsyncTypes = 1993, ERR_BadAsyncLacksBody = 1994, ERR_BadAwaitInQuery = 1995, ERR_BadAwaitInLock = 1996, ERR_TaskRetNoObjectRequired = 1997, WRN_AsyncLacksAwaits = 1998, ERR_FileNotFound = 2001, WRN_FileAlreadyIncluded = 2002, ERR_DuplicateResponseFile = 2003, ERR_NoFileSpec = 2005, ERR_SwitchNeedsString = 2006, ERR_BadSwitch = 2007, WRN_NoSources = 2008, ERR_OpenResponseFile = 2011, ERR_CantOpenFileWrite = 2012, ERR_BadBaseNumber = 2013, WRN_UseNewSwitch = 2014, //unused but preserved to keep compat with /nowarn:2014 ERR_BinaryFile = 2015, FTL_BadCodepage = 2016, ERR_NoMainOnDLL = 2017, //FTL_NoMessagesDLL = 2018, FTL_InvalidTarget = 2019, //ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once! FTL_InvalidInputFileName = 2021, //ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once! WRN_NoConfigNotOnCommandLine = 2023, ERR_BadFileAlignment = 2024, //ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn. //ERR_SourceMapFileBinary = 2027, WRN_DefineIdentifierRequired = 2029, //ERR_InvalidSourceMap = 2030, //ERR_NoSourceMapFile = 2031, ERR_IllegalOptionChar = 2032, FTL_OutputFileExists = 2033, ERR_OneAliasPerReference = 2034, ERR_SwitchNeedsNumber = 2035, ERR_MissingDebugSwitch = 2036, ERR_ComRefCallInExpressionTree = 2037, WRN_BadUILang = 2038, WRN_CLS_NoVarArgs = 3000, WRN_CLS_BadArgType = 3001, WRN_CLS_BadReturnType = 3002, WRN_CLS_BadFieldPropType = 3003, WRN_CLS_BadUnicode = 3004, //unused but preserved to keep compat with /nowarn:3004 WRN_CLS_BadIdentifierCase = 3005, WRN_CLS_OverloadRefOut = 3006, WRN_CLS_OverloadUnnamed = 3007, WRN_CLS_BadIdentifier = 3008, WRN_CLS_BadBase = 3009, WRN_CLS_BadInterfaceMember = 3010, WRN_CLS_NoAbstractMembers = 3011, WRN_CLS_NotOnModules = 3012, WRN_CLS_ModuleMissingCLS = 3013, WRN_CLS_AssemblyNotCLS = 3014, WRN_CLS_BadAttributeType = 3015, WRN_CLS_ArrayArgumentToAttribute = 3016, WRN_CLS_NotOnModules2 = 3017, WRN_CLS_IllegalTrueInFalse = 3018, WRN_CLS_MeaninglessOnPrivateType = 3019, WRN_CLS_AssemblyNotCLS2 = 3021, WRN_CLS_MeaninglessOnParam = 3022, WRN_CLS_MeaninglessOnReturn = 3023, WRN_CLS_BadTypeVar = 3024, WRN_CLS_VolatileField = 3026, WRN_CLS_BadInterface = 3027, // Errors introduced in C# 5 are in the range 4000-4999 // 4000 unused ERR_BadAwaitArgIntrinsic = 4001, // 4002 unused ERR_BadAwaitAsIdentifier = 4003, ERR_AwaitInUnsafeContext = 4004, ERR_UnsafeAsyncArgType = 4005, ERR_VarargsAsync = 4006, ERR_ByRefTypeAndAwait = 4007, ERR_BadAwaitArgVoidCall = 4008, ERR_MainCantBeAsync = 4009, ERR_CantConvAsyncAnonFuncReturns = 4010, ERR_BadAwaiterPattern = 4011, ERR_BadSpecialByRefLocal = 4012, ERR_SpecialByRefInLambda = 4013, WRN_UnobservedAwaitableExpression = 4014, ERR_SynchronizedAsyncMethod = 4015, ERR_BadAsyncReturnExpression = 4016, ERR_NoConversionForCallerLineNumberParam = 4017, ERR_NoConversionForCallerFilePathParam = 4018, ERR_NoConversionForCallerMemberNameParam = 4019, ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020, ERR_BadCallerFilePathParamWithoutDefaultValue = 4021, ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022, ERR_BadPrefer32OnLib = 4023, WRN_CallerLineNumberParamForUnconsumedLocation = 4024, WRN_CallerFilePathParamForUnconsumedLocation = 4025, WRN_CallerMemberNameParamForUnconsumedLocation = 4026, ERR_DoesntImplementAwaitInterface = 4027, ERR_BadAwaitArg_NeedSystem = 4028, ERR_CantReturnVoid = 4029, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031, ERR_BadAwaitWithoutAsyncMethod = 4032, ERR_BadAwaitWithoutVoidAsyncMethod = 4033, ERR_BadAwaitWithoutAsyncLambda = 4034, // ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn ERR_NoSuchMemberOrExtensionNeedUsing = 4036, WRN_UnknownOption = 5000, //unused in Roslyn ERR_NoEntryPoint = 5001, // There is space in the range of error codes from 7000-8999 that // we can use for new errors in post-Dev10. ERR_UnexpectedAliasedName = 7000, ERR_UnexpectedGenericName = 7002, ERR_UnexpectedUnboundGenericName = 7003, ERR_GlobalStatement = 7006, ERR_BadUsingType = 7007, ERR_ReservedAssemblyName = 7008, ERR_PPReferenceFollowsToken = 7009, ERR_ExpectedPPFile = 7010, ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011, ERR_NameNotInContextPossibleMissingReference = 7012, WRN_MetadataNameTooLong = 7013, ERR_AttributesNotAllowed = 7014, ERR_ExternAliasNotAllowed = 7015, ERR_ConflictingAliasAndDefinition = 7016, ERR_GlobalDefinitionOrStatementExpected = 7017, ERR_ExpectedSingleScript = 7018, ERR_RecursivelyTypedVariable = 7019, ERR_ReturnNotAllowedInScript = 7020, ERR_NamespaceNotAllowedInScript = 7021, WRN_MainIgnored = 7022, ERR_StaticInAsOrIs = 7023, ERR_InvalidDelegateType = 7024, ERR_BadVisEventType = 7025, ERR_GlobalAttributesNotAllowed = 7026, ERR_PublicKeyFileFailure = 7027, ERR_PublicKeyContainerFailure = 7028, ERR_FriendRefSigningMismatch = 7029, ERR_CannotPassNullForFriendAssembly = 7030, ERR_SignButNoPrivateKey = 7032, WRN_DelaySignButNoKey = 7033, ERR_InvalidVersionFormat = 7034, WRN_InvalidVersionFormat = 7035, ERR_NoCorrespondingArgument = 7036, // Moot: WRN_DestructorIsNotFinalizer = 7037, ERR_ModuleEmitFailure = 7038, ERR_NameIllegallyOverrides2 = 7039, ERR_NameIllegallyOverrides3 = 7040, ERR_ResourceFileNameNotUnique = 7041, ERR_DllImportOnGenericMethod = 7042, ERR_LibraryMethodNotFound = 7043, ERR_LibraryMethodNotUnique = 7044, ERR_ParameterNotValidForType = 7045, ERR_AttributeParameterRequired1 = 7046, ERR_AttributeParameterRequired2 = 7047, ERR_SecurityAttributeMissingAction = 7048, ERR_SecurityAttributeInvalidAction = 7049, ERR_SecurityAttributeInvalidActionAssembly = 7050, ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051, ERR_PrincipalPermissionInvalidAction = 7052, ERR_FeatureNotValidInExpressionTree = 7053, ERR_MarshalUnmanagedTypeNotValidForFields = 7054, ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055, ERR_PermissionSetAttributeInvalidFile = 7056, ERR_PermissionSetAttributeFileReadError = 7057, ERR_InvalidVersionFormat2 = 7058, ERR_InvalidAssemblyCultureForExe = 7059, ERR_AsyncBeforeVersionFive = 7060, ERR_DuplicateAttributeInNetModule = 7061, //WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning ERR_CantOpenIcon = 7064, ERR_ErrorBuildingWin32Resources = 7065, ERR_IteratorInInteractive = 7066, ERR_BadAttributeParamDefaultArgument = 7067, ERR_MissingTypeInSource = 7068, ERR_MissingTypeInAssembly = 7069, ERR_SecurityAttributeInvalidTarget = 7070, ERR_InvalidAssemblyName = 7071, ERR_PartialTypesBeforeVersionTwo = 7072, ERR_PartialMethodsBeforeVersionThree = 7073, ERR_QueryBeforeVersionThree = 7074, ERR_AnonymousTypeBeforeVersionThree = 7075, ERR_ImplicitArrayBeforeVersionThree = 7076, ERR_ObjectInitializerBeforeVersionThree = 7077, ERR_LambdaBeforeVersionThree = 7078, ERR_NoTypeDefFromModule = 7079, WRN_CallerFilePathPreferredOverCallerMemberName = 7080, WRN_CallerLineNumberPreferredOverCallerMemberName = 7081, WRN_CallerLineNumberPreferredOverCallerFilePath = 7082, ERR_InvalidDynamicCondition = 7083, ERR_WinRtEventPassedByRef = 7084, ERR_ByRefReturnUnsupported = 7085, ERR_NetModuleNameMismatch = 7086, ERR_BadCompilationOption = 7087, ERR_BadCompilationOptionValue = 7088, ERR_BadAppConfigPath = 7089, WRN_AssemblyAttributeFromModuleIsOverridden = 7090, ERR_CmdOptionConflictsSource = 7091, ERR_FixedBufferTooManyDimensions = 7092, ERR_CantReadConfigFile = 7093, ERR_NotYetImplementedInRoslyn = 8000, WRN_UnimplementedCommandLineSwitch = 8001, ERR_ReferencedAssemblyDoesNotHaveStrongName = 8002, ERR_InvalidSignaturePublicKey = 8003, ERR_ExportedTypeConflictsWithDeclaration = 8004, ERR_ExportedTypesConflict = 8005, ERR_ForwardedTypeConflictsWithDeclaration = 8006, ERR_ForwardedTypesConflict = 8007, ERR_ForwardedTypeConflictsWithExportedType = 8008, WRN_RefCultureMismatch = 8009, ERR_AgnosticToMachineModule = 8010, ERR_ConflictingMachineModule = 8011, WRN_ConflictingMachineAssembly = 8012, ERR_CryptoHashFailed = 8013, ERR_MissingNetModuleReference = 8014, // Values in the range 10000-14000 are used for ""Code Analysis"" issues previously reported by FXCop WRN_CA2000_DisposeObjectsBeforeLosingScope1 = 10000, WRN_CA2000_DisposeObjectsBeforeLosingScope2 = 10001, WRN_CA2202_DoNotDisposeObjectsMultipleTimes = 10002 } /// <summary> /// Values for ErrorCode/ERRID that are used internally by the compiler but are not exposed. /// </summary> internal static class InternalErrorCode { /// <summary> /// The code has yet to be determined. /// </summary> public const int Unknown = -1; /// <summary> /// The code was lazily determined and does not need to be reported. /// </summary> public const int Void = -2; } } } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyIL("ConsoleApplication24.Program.IsWarning", @" { // Code size 1889 (0x761) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x32b IL_0006: bgt IL_0300 IL_000b: ldarg.0 IL_000c: ldc.i4 0x1ad IL_0011: bgt IL_0154 IL_0016: ldarg.0 IL_0017: ldc.i4 0xb8 IL_001c: bgt IL_00a9 IL_0021: ldarg.0 IL_0022: ldc.i4.s 109 IL_0024: bgt.s IL_005f IL_0026: ldarg.0 IL_0027: ldc.i4.s 67 IL_0029: bgt.s IL_0040 IL_002b: ldarg.0 IL_002c: ldc.i4.s 28 IL_002e: beq IL_075d IL_0033: ldarg.0 IL_0034: ldc.i4.s 67 IL_0036: beq IL_075d IL_003b: br IL_075f IL_0040: ldarg.0 IL_0041: ldc.i4.s 78 IL_0043: beq IL_075d IL_0048: ldarg.0 IL_0049: ldc.i4.s 105 IL_004b: beq IL_075d IL_0050: ldarg.0 IL_0051: ldc.i4.s 108 IL_0053: sub IL_0054: ldc.i4.1 IL_0055: ble.un IL_075d IL_005a: br IL_075f IL_005f: ldarg.0 IL_0060: ldc.i4 0xa2 IL_0065: bgt.s IL_007f IL_0067: ldarg.0 IL_0068: ldc.i4.s 114 IL_006a: beq IL_075d IL_006f: ldarg.0 IL_0070: ldc.i4 0xa2 IL_0075: beq IL_075d IL_007a: br IL_075f IL_007f: ldarg.0 IL_0080: ldc.i4 0xa4 IL_0085: beq IL_075d IL_008a: ldarg.0 IL_008b: ldc.i4 0xa8 IL_0090: sub IL_0091: ldc.i4.1 IL_0092: ble.un IL_075d IL_0097: ldarg.0 IL_0098: ldc.i4 0xb7 IL_009d: sub IL_009e: ldc.i4.1 IL_009f: ble.un IL_075d IL_00a4: br IL_075f IL_00a9: ldarg.0 IL_00aa: ldc.i4 0x118 IL_00af: bgt.s IL_00fe IL_00b1: ldarg.0 IL_00b2: ldc.i4 0xcf IL_00b7: bgt.s IL_00d4 IL_00b9: ldarg.0 IL_00ba: ldc.i4 0xc5 IL_00bf: beq IL_075d IL_00c4: ldarg.0 IL_00c5: ldc.i4 0xcf IL_00ca: beq IL_075d IL_00cf: br IL_075f IL_00d4: ldarg.0 IL_00d5: ldc.i4 0xdb IL_00da: beq IL_075d IL_00df: ldarg.0 IL_00e0: ldc.i4 0xfb IL_00e5: sub IL_00e6: ldc.i4.2 IL_00e7: ble.un IL_075d IL_00ec: ldarg.0 IL_00ed: ldc.i4 0x116 IL_00f2: sub IL_00f3: ldc.i4.2 IL_00f4: ble.un IL_075d IL_00f9: br IL_075f IL_00fe: ldarg.0 IL_00ff: ldc.i4 0x19e IL_0104: bgt.s IL_012c IL_0106: ldarg.0 IL_0107: ldc.i4 0x11a IL_010c: beq IL_075d IL_0111: ldarg.0 IL_0112: ldc.i4 0x192 IL_0117: beq IL_075d IL_011c: ldarg.0 IL_011d: ldc.i4 0x19e IL_0122: beq IL_075d IL_0127: br IL_075f IL_012c: ldarg.0 IL_012d: ldc.i4 0x1a3 IL_0132: sub IL_0133: ldc.i4.1 IL_0134: ble.un IL_075d IL_0139: ldarg.0 IL_013a: ldc.i4 0x1a6 IL_013f: beq IL_075d IL_0144: ldarg.0 IL_0145: ldc.i4 0x1ad IL_014a: beq IL_075d IL_014f: br IL_075f IL_0154: ldarg.0 IL_0155: ldc.i4 0x274 IL_015a: bgt IL_0224 IL_015f: ldarg.0 IL_0160: ldc.i4 0x1d9 IL_0165: bgt.s IL_01db IL_0167: ldarg.0 IL_0168: ldc.i4 0x1b8 IL_016d: bgt.s IL_018c IL_016f: ldarg.0 IL_0170: ldc.i4 0x1b3 IL_0175: sub IL_0176: ldc.i4.2 IL_0177: ble.un IL_075d IL_017c: ldarg.0 IL_017d: ldc.i4 0x1b8 IL_0182: beq IL_075d IL_0187: br IL_075f IL_018c: ldarg.0 IL_018d: ldc.i4 0x1bc IL_0192: beq IL_075d IL_0197: ldarg.0 IL_0198: ldc.i4 0x1ca IL_019d: beq IL_075d IL_01a2: ldarg.0 IL_01a3: ldc.i4 0x1d0 IL_01a8: sub IL_01a9: switch ( IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d) IL_01d6: br IL_075f IL_01db: ldarg.0 IL_01dc: ldc.i4 0x264 IL_01e1: bgt.s IL_01fe IL_01e3: ldarg.0 IL_01e4: ldc.i4 0x25a IL_01e9: beq IL_075d IL_01ee: ldarg.0 IL_01ef: ldc.i4 0x264 IL_01f4: beq IL_075d IL_01f9: br IL_075f IL_01fe: ldarg.0 IL_01ff: ldc.i4 0x26a IL_0204: beq IL_075d IL_0209: ldarg.0 IL_020a: ldc.i4 0x272 IL_020f: beq IL_075d IL_0214: ldarg.0 IL_0215: ldc.i4 0x274 IL_021a: beq IL_075d IL_021f: br IL_075f IL_0224: ldarg.0 IL_0225: ldc.i4 0x2a3 IL_022a: bgt.s IL_02aa IL_022c: ldarg.0 IL_022d: ldc.i4 0x295 IL_0232: bgt.s IL_0284 IL_0234: ldarg.0 IL_0235: ldc.i4 0x282 IL_023a: beq IL_075d IL_023f: ldarg.0 IL_0240: ldc.i4 0x289 IL_0245: sub IL_0246: switch ( IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d) IL_027f: br IL_075f IL_0284: ldarg.0 IL_0285: ldc.i4 0x299 IL_028a: beq IL_075d IL_028f: ldarg.0 IL_0290: ldc.i4 0x2a0 IL_0295: beq IL_075d IL_029a: ldarg.0 IL_029b: ldc.i4 0x2a3 IL_02a0: beq IL_075d IL_02a5: br IL_075f IL_02aa: ldarg.0 IL_02ab: ldc.i4 0x2b5 IL_02b0: bgt.s IL_02da IL_02b2: ldarg.0 IL_02b3: ldc.i4 0x2a7 IL_02b8: sub IL_02b9: ldc.i4.1 IL_02ba: ble.un IL_075d IL_02bf: ldarg.0 IL_02c0: ldc.i4 0x2ac IL_02c5: beq IL_075d IL_02ca: ldarg.0 IL_02cb: ldc.i4 0x2b5 IL_02d0: beq IL_075d IL_02d5: br IL_075f IL_02da: ldarg.0 IL_02db: ldc.i4 0x2d8 IL_02e0: beq IL_075d IL_02e5: ldarg.0 IL_02e6: ldc.i4 0x329 IL_02eb: beq IL_075d IL_02f0: ldarg.0 IL_02f1: ldc.i4 0x32b IL_02f6: beq IL_075d IL_02fb: br IL_075f IL_0300: ldarg.0 IL_0301: ldc.i4 0x7bd IL_0306: bgt IL_05d1 IL_030b: ldarg.0 IL_030c: ldc.i4 0x663 IL_0311: bgt IL_0451 IL_0316: ldarg.0 IL_0317: ldc.i4 0x5f2 IL_031c: bgt.s IL_038e IL_031e: ldarg.0 IL_031f: ldc.i4 0x406 IL_0324: bgt.s IL_0341 IL_0326: ldarg.0 IL_0327: ldc.i4 0x338 IL_032c: beq IL_075d IL_0331: ldarg.0 IL_0332: ldc.i4 0x406 IL_0337: beq IL_075d IL_033c: br IL_075f IL_0341: ldarg.0 IL_0342: ldc.i4 0x422 IL_0347: sub IL_0348: switch ( IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d) IL_0371: ldarg.0 IL_0372: ldc.i4 0x4b0 IL_0377: sub IL_0378: ldc.i4.4 IL_0379: ble.un IL_075d IL_037e: ldarg.0 IL_037f: ldc.i4 0x5f2 IL_0384: beq IL_075d IL_0389: br IL_075f IL_038e: ldarg.0 IL_038f: ldc.i4 0x647 IL_0394: bgt IL_0429 IL_0399: ldarg.0 IL_039a: ldc.i4 0x622 IL_039f: sub IL_03a0: switch ( IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d, IL_075f, IL_075d) IL_0419: ldarg.0 IL_041a: ldc.i4 0x647 IL_041f: beq IL_075d IL_0424: br IL_075f IL_0429: ldarg.0 IL_042a: ldc.i4 0x64a IL_042f: beq IL_075d IL_0434: ldarg.0 IL_0435: ldc.i4 0x650 IL_043a: beq IL_075d IL_043f: ldarg.0 IL_0440: ldc.i4 0x661 IL_0445: sub IL_0446: ldc.i4.2 IL_0447: ble.un IL_075d IL_044c: br IL_075f IL_0451: ldarg.0 IL_0452: ldc.i4 0x6c7 IL_0457: bgt IL_057b IL_045c: ldarg.0 IL_045d: ldc.i4 0x67b IL_0462: bgt.s IL_0481 IL_0464: ldarg.0 IL_0465: ldc.i4 0x66d IL_046a: beq IL_075d IL_046f: ldarg.0 IL_0470: ldc.i4 0x67a IL_0475: sub IL_0476: ldc.i4.1 IL_0477: ble.un IL_075d IL_047c: br IL_075f IL_0481: ldarg.0 IL_0482: ldc.i4 0x684 IL_0487: sub IL_0488: switch ( IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d) IL_0541: ldarg.0 IL_0542: ldc.i4 0x6b5 IL_0547: sub IL_0548: switch ( IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d) IL_0569: ldarg.0 IL_056a: ldc.i4 0x6c6 IL_056f: sub IL_0570: ldc.i4.1 IL_0571: ble.un IL_075d IL_0576: br IL_075f IL_057b: ldarg.0 IL_057c: ldc.i4 0x787 IL_0581: bgt.s IL_05a9 IL_0583: ldarg.0 IL_0584: ldc.i4 0x6e2 IL_0589: beq IL_075d IL_058e: ldarg.0 IL_058f: ldc.i4 0x6e5 IL_0594: beq IL_075d IL_0599: ldarg.0 IL_059a: ldc.i4 0x787 IL_059f: beq IL_075d IL_05a4: br IL_075f IL_05a9: ldarg.0 IL_05aa: ldc.i4 0x7a4 IL_05af: sub IL_05b0: ldc.i4.1 IL_05b1: ble.un IL_075d IL_05b6: ldarg.0 IL_05b7: ldc.i4 0x7b6 IL_05bc: beq IL_075d IL_05c1: ldarg.0 IL_05c2: ldc.i4 0x7bd IL_05c7: beq IL_075d IL_05cc: br IL_075f IL_05d1: ldarg.0 IL_05d2: ldc.i4 0xfba IL_05d7: bgt IL_06e3 IL_05dc: ldarg.0 IL_05dd: ldc.i4 0x7e7 IL_05e2: bgt.s IL_062d IL_05e4: ldarg.0 IL_05e5: ldc.i4 0x7d2 IL_05ea: bgt.s IL_0607 IL_05ec: ldarg.0 IL_05ed: ldc.i4 0x7ce IL_05f2: beq IL_075d IL_05f7: ldarg.0 IL_05f8: ldc.i4 0x7d2 IL_05fd: beq IL_075d IL_0602: br IL_075f IL_0607: ldarg.0 IL_0608: ldc.i4 0x7d8 IL_060d: beq IL_075d IL_0612: ldarg.0 IL_0613: ldc.i4 0x7de IL_0618: beq IL_075d IL_061d: ldarg.0 IL_061e: ldc.i4 0x7e7 IL_0623: beq IL_075d IL_0628: br IL_075f IL_062d: ldarg.0 IL_062e: ldc.i4 0x7f6 IL_0633: bgt.s IL_0650 IL_0635: ldarg.0 IL_0636: ldc.i4 0x7ed IL_063b: beq IL_075d IL_0640: ldarg.0 IL_0641: ldc.i4 0x7f6 IL_0646: beq IL_075d IL_064b: br IL_075f IL_0650: ldarg.0 IL_0651: ldc.i4 0xbb8 IL_0656: sub IL_0657: switch ( IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d) IL_06cc: ldarg.0 IL_06cd: ldc.i4 0xfae IL_06d2: beq IL_075d IL_06d7: ldarg.0 IL_06d8: ldc.i4 0xfb8 IL_06dd: sub IL_06de: ldc.i4.2 IL_06df: ble.un.s IL_075d IL_06e1: br.s IL_075f IL_06e3: ldarg.0 IL_06e4: ldc.i4 0x1b7b IL_06e9: bgt.s IL_071f IL_06eb: ldarg.0 IL_06ec: ldc.i4 0x1b65 IL_06f1: bgt.s IL_0705 IL_06f3: ldarg.0 IL_06f4: ldc.i4 0x1388 IL_06f9: beq.s IL_075d IL_06fb: ldarg.0 IL_06fc: ldc.i4 0x1b65 IL_0701: beq.s IL_075d IL_0703: br.s IL_075f IL_0705: ldarg.0 IL_0706: ldc.i4 0x1b6e IL_070b: beq.s IL_075d IL_070d: ldarg.0 IL_070e: ldc.i4 0x1b79 IL_0713: beq.s IL_075d IL_0715: ldarg.0 IL_0716: ldc.i4 0x1b7b IL_071b: beq.s IL_075d IL_071d: br.s IL_075f IL_071f: ldarg.0 IL_0720: ldc.i4 0x1f41 IL_0725: bgt.s IL_0743 IL_0727: ldarg.0 IL_0728: ldc.i4 0x1ba8 IL_072d: sub IL_072e: ldc.i4.2 IL_072f: ble.un.s IL_075d IL_0731: ldarg.0 IL_0732: ldc.i4 0x1bb2 IL_0737: beq.s IL_075d IL_0739: ldarg.0 IL_073a: ldc.i4 0x1f41 IL_073f: beq.s IL_075d IL_0741: br.s IL_075f IL_0743: ldarg.0 IL_0744: ldc.i4 0x1f49 IL_0749: beq.s IL_075d IL_074b: ldarg.0 IL_074c: ldc.i4 0x1f4c IL_0751: beq.s IL_075d IL_0753: ldarg.0 IL_0754: ldc.i4 0x2710 IL_0759: sub IL_075a: ldc.i4.2 IL_075b: bgt.un.s IL_075f IL_075d: ldc.i4.1 IL_075e: ret IL_075f: ldc.i4.0 IL_0760: ret }"); } [Fact] public void StringSwitch() { var text = @"using System; public class Test { public static void Main() { Console.WriteLine(M(""Orange"")); } public static int M(string s) { switch (s) { case ""Black"": return 0; case ""Brown"": return 1; case ""Red"": return 2; case ""Orange"": return 3; case ""Yellow"": return 4; case ""Green"": return 5; case ""Blue"": return 6; case ""Violet"": return 7; case ""Grey"": case ""Gray"": return 8; case ""White"": return 9; default: throw new ArgumentException(s); } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "3"); compVerifier.VerifyIL("Test.M", @" { // Code size 368 (0x170) .maxstack 2 .locals init (uint V_0) IL_0000: ldarg.0 IL_0001: call ""ComputeStringHash"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4 0x6ceb2d06 IL_000d: bgt.un.s IL_0055 IL_000f: ldloc.0 IL_0010: ldc.i4 0x2b043744 IL_0015: bgt.un.s IL_002f IL_0017: ldloc.0 IL_0018: ldc.i4 0x2b8b9cf IL_001d: beq IL_00b2 IL_0022: ldloc.0 IL_0023: ldc.i4 0x2b043744 IL_0028: beq.s IL_009d IL_002a: br IL_0169 IL_002f: ldloc.0 IL_0030: ldc.i4 0x32bdf8c6 IL_0035: beq IL_0127 IL_003a: ldloc.0 IL_003b: ldc.i4 0x3ac6ffba IL_0040: beq IL_0136 IL_0045: ldloc.0 IL_0046: ldc.i4 0x6ceb2d06 IL_004b: beq IL_0145 IL_0050: br IL_0169 IL_0055: ldloc.0 IL_0056: ldc.i4 0xa953c75c IL_005b: bgt.un.s IL_007d IL_005d: ldloc.0 IL_005e: ldc.i4 0x727b390b IL_0063: beq.s IL_00dc IL_0065: ldloc.0 IL_0066: ldc.i4 0xa37f187c IL_006b: beq.s IL_00c7 IL_006d: ldloc.0 IL_006e: ldc.i4 0xa953c75c IL_0073: beq IL_00fa IL_0078: br IL_0169 IL_007d: ldloc.0 IL_007e: ldc.i4 0xd9cdec69 IL_0083: beq.s IL_00eb IL_0085: ldloc.0 IL_0086: ldc.i4 0xe9dd1fed IL_008b: beq.s IL_0109 IL_008d: ldloc.0 IL_008e: ldc.i4 0xf03bdf12 IL_0093: beq IL_0118 IL_0098: br IL_0169 IL_009d: ldarg.0 IL_009e: ldstr ""Black"" IL_00a3: call ""bool string.op_Equality(string, string)"" IL_00a8: brtrue IL_0154 IL_00ad: br IL_0169 IL_00b2: ldarg.0 IL_00b3: ldstr ""Brown"" IL_00b8: call ""bool string.op_Equality(string, string)"" IL_00bd: brtrue IL_0156 IL_00c2: br IL_0169 IL_00c7: ldarg.0 IL_00c8: ldstr ""Red"" IL_00cd: call ""bool string.op_Equality(string, string)"" IL_00d2: brtrue IL_0158 IL_00d7: br IL_0169 IL_00dc: ldarg.0 IL_00dd: ldstr ""Orange"" IL_00e2: call ""bool string.op_Equality(string, string)"" IL_00e7: brtrue.s IL_015a IL_00e9: br.s IL_0169 IL_00eb: ldarg.0 IL_00ec: ldstr ""Yellow"" IL_00f1: call ""bool string.op_Equality(string, string)"" IL_00f6: brtrue.s IL_015c IL_00f8: br.s IL_0169 IL_00fa: ldarg.0 IL_00fb: ldstr ""Green"" IL_0100: call ""bool string.op_Equality(string, string)"" IL_0105: brtrue.s IL_015e IL_0107: br.s IL_0169 IL_0109: ldarg.0 IL_010a: ldstr ""Blue"" IL_010f: call ""bool string.op_Equality(string, string)"" IL_0114: brtrue.s IL_0160 IL_0116: br.s IL_0169 IL_0118: ldarg.0 IL_0119: ldstr ""Violet"" IL_011e: call ""bool string.op_Equality(string, string)"" IL_0123: brtrue.s IL_0162 IL_0125: br.s IL_0169 IL_0127: ldarg.0 IL_0128: ldstr ""Grey"" IL_012d: call ""bool string.op_Equality(string, string)"" IL_0132: brtrue.s IL_0164 IL_0134: br.s IL_0169 IL_0136: ldarg.0 IL_0137: ldstr ""Gray"" IL_013c: call ""bool string.op_Equality(string, string)"" IL_0141: brtrue.s IL_0164 IL_0143: br.s IL_0169 IL_0145: ldarg.0 IL_0146: ldstr ""White"" IL_014b: call ""bool string.op_Equality(string, string)"" IL_0150: brtrue.s IL_0166 IL_0152: br.s IL_0169 IL_0154: ldc.i4.0 IL_0155: ret IL_0156: ldc.i4.1 IL_0157: ret IL_0158: ldc.i4.2 IL_0159: ret IL_015a: ldc.i4.3 IL_015b: ret IL_015c: ldc.i4.4 IL_015d: ret IL_015e: ldc.i4.5 IL_015f: ret IL_0160: ldc.i4.6 IL_0161: ret IL_0162: ldc.i4.7 IL_0163: ret IL_0164: ldc.i4.8 IL_0165: ret IL_0166: ldc.i4.s 9 IL_0168: ret IL_0169: ldarg.0 IL_016a: newobj ""System.ArgumentException..ctor(string)"" IL_016f: throw }"); } #endregion # region "Data flow analysis tests" [Fact] public void DefiniteAssignmentOnAllControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int n = 3; int goo; // unassigned goo switch (n) { case 1: case 2: goo = n; break; case 3: default: goo = 0; break; } Console.Write(goo); // goo must be definitely assigned here return goo; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("SwitchTest.Main", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (int V_0, //n int V_1) //goo IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: ldc.i4.1 IL_0006: ble.un.s IL_000e IL_0008: ldloc.0 IL_0009: ldc.i4.3 IL_000a: beq.s IL_0012 IL_000c: br.s IL_0012 IL_000e: ldloc.0 IL_000f: stloc.1 IL_0010: br.s IL_0014 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: call ""void System.Console.Write(int)"" IL_001a: ldloc.1 IL_001b: ret }" ); } [Fact] public void ComplexControlFlow_DefiniteAssignmentOnAllControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int n = 3; int cost = 0; int goo; // unassigned goo switch (n) { case 1: cost = 1; goo = n; break; case 2: cost = 2; goto case 1; case 3: cost = 3; if(cost > n) { goo = n - 1; } else { goto case 2; } break; default: cost = 4; goo = n - 1; break; } if (goo != n) // goo must be reported as definitely assigned { Console.Write(goo); } else { --cost; } Console.Write(cost); // should output 0 return cost; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("SwitchTest.Main", @"{ // Code size 78 (0x4e) .maxstack 2 .locals init (int V_0, //n int V_1, //cost int V_2) //goo IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldc.i4.1 IL_0006: sub IL_0007: switch ( IL_001a, IL_0020, IL_0024) IL_0018: br.s IL_0030 IL_001a: ldc.i4.1 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: stloc.2 IL_001e: br.s IL_0036 IL_0020: ldc.i4.2 IL_0021: stloc.1 IL_0022: br.s IL_001a IL_0024: ldc.i4.3 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldloc.0 IL_0028: ble.s IL_0020 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: sub IL_002d: stloc.2 IL_002e: br.s IL_0036 IL_0030: ldc.i4.4 IL_0031: stloc.1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: sub IL_0035: stloc.2 IL_0036: ldloc.2 IL_0037: ldloc.0 IL_0038: beq.s IL_0042 IL_003a: ldloc.2 IL_003b: call ""void System.Console.Write(int)"" IL_0040: br.s IL_0046 IL_0042: ldloc.1 IL_0043: ldc.i4.1 IL_0044: sub IL_0045: stloc.1 IL_0046: ldloc.1 IL_0047: call ""void System.Console.Write(int)"" IL_004c: ldloc.1 IL_004d: ret }" ); } [Fact] public void ComplexControlFlow_NoAssignmentOnlyOnUnreachableControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int goo; // unassigned goo switch (3) { case 1: mylabel: try { throw new System.ApplicationException(); } catch(Exception) { goo = 0; } break; case 2: goto mylabel; case 3: if (true) { goto case 2; } break; case 4: break; } Console.Write(goo); // goo should be definitely assigned here return goo; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (27,17): warning CS0162: Unreachable code detected // break; Diagnostic(ErrorCode.WRN_UnreachableCode, "break"), // (29,17): warning CS0162: Unreachable code detected // break; Diagnostic(ErrorCode.WRN_UnreachableCode, "break")); compVerifier.VerifyIL("SwitchTest.Main", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) //goo IL_0000: nop .try { IL_0001: newobj ""System.ApplicationException..ctor()"" IL_0006: throw } catch System.Exception { IL_0007: pop IL_0008: ldc.i4.0 IL_0009: stloc.0 IL_000a: leave.s IL_000c } IL_000c: ldloc.0 IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldloc.0 IL_0013: ret }" ); } #endregion #region "Control flow analysis and warning tests" [Fact] public void CS0469_NoImplicitConversionWarning() { var text = @"using System; class A { static void Goo(DayOfWeek x) { switch (x) { case DayOfWeek.Monday: goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' } } static void Main() {} } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyDiagnostics( // (10,17): warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' // goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 1;").WithArguments("System.DayOfWeek")); compVerifier.VerifyIL("A.Goo", @" { // Code size 7 (0x7) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_0006 IL_0004: br.s IL_0004 IL_0006: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_01() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 2; switch (true) { case true: ret = 0; break; case false: // unreachable case label ret = 1; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (14,8): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret")); compVerifier.VerifyIL("Test.Main", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""void System.Console.Write(int)"" IL_000a: ldloc.0 IL_000b: ret } " ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { default: // unreachable default label ret = 1; break; case true: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (11,17): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 17) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""void System.Console.Write(int)"" IL_000a: ldloc.0 IL_000b: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_03() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { switch (1) { case 1: return 0; } return 1; // unreachable code } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (19,5): warning CS0162: Unreachable code detected // return 1; // unreachable code Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(19, 5)); compVerifier.VerifyIL("Test.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_04() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; switch (1) // no matching case/default label { case 2: // unreachable code ret = 1; break; } Console.Write(ret); return(ret); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (11,9): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 9) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call ""void System.Console.Write(int)"" IL_0008: ldloc.0 IL_0009: ret }" ); } [Fact] public void CS1522_EmptySwitch() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; switch (true) { } Console.Write(ret); return(0); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (7,23): warning CS1522: Empty switch block // switch (true) { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 23) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ldc.i4.0 IL_0007: ret }" ); } [WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")] [Fact] public void DifferentStrategiesForDifferentSwitches() { var text = @" using System; public class Test { public static void Main(string [] args) { switch(args[0]) { case ""A"": Console.Write(1); break; } switch(args[1]) { case ""B"": Console.Write(2); break; case ""C"": Console.Write(3); break; case ""D"": Console.Write(4); break; case ""E"": Console.Write(5); break; case ""F"": Console.Write(6); break; case ""G"": Console.Write(7); break; case ""H"": Console.Write(8); break; case ""I"": Console.Write(9); break; case ""J"": Console.Write(10); break; } } }"; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE")); CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 326 (0x146) .maxstack 2 .locals init (string V_0, uint V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: ldstr ""A"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brfalse.s IL_0015 IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: ldarg.0 IL_0016: ldc.i4.1 IL_0017: ldelem.ref IL_0018: stloc.0 IL_0019: ldloc.0 IL_001a: call ""ComputeStringHash"" IL_001f: stloc.1 IL_0020: ldloc.1 IL_0021: ldc.i4 0xc30bf539 IL_0026: bgt.un.s IL_0055 IL_0028: ldloc.1 IL_0029: ldc.i4 0xc10bf213 IL_002e: bgt.un.s IL_0041 IL_0030: ldloc.1 IL_0031: ldc.i4 0xc00bf080 IL_0036: beq.s IL_00b1 IL_0038: ldloc.1 IL_0039: ldc.i4 0xc10bf213 IL_003e: beq.s IL_00a3 IL_0040: ret IL_0041: ldloc.1 IL_0042: ldc.i4 0xc20bf3a6 IL_0047: beq IL_00cd IL_004c: ldloc.1 IL_004d: ldc.i4 0xc30bf539 IL_0052: beq.s IL_00bf IL_0054: ret IL_0055: ldloc.1 IL_0056: ldc.i4 0xc70bfb85 IL_005b: bgt.un.s IL_006e IL_005d: ldloc.1 IL_005e: ldc.i4 0xc60bf9f2 IL_0063: beq.s IL_0095 IL_0065: ldloc.1 IL_0066: ldc.i4 0xc70bfb85 IL_006b: beq.s IL_0087 IL_006d: ret IL_006e: ldloc.1 IL_006f: ldc.i4 0xcc0c0364 IL_0074: beq.s IL_00e9 IL_0076: ldloc.1 IL_0077: ldc.i4 0xcd0c04f7 IL_007c: beq.s IL_00db IL_007e: ldloc.1 IL_007f: ldc.i4 0xcf0c081d IL_0084: beq.s IL_00f7 IL_0086: ret IL_0087: ldloc.0 IL_0088: ldstr ""B"" IL_008d: call ""bool string.op_Equality(string, string)"" IL_0092: brtrue.s IL_0105 IL_0094: ret IL_0095: ldloc.0 IL_0096: ldstr ""C"" IL_009b: call ""bool string.op_Equality(string, string)"" IL_00a0: brtrue.s IL_010c IL_00a2: ret IL_00a3: ldloc.0 IL_00a4: ldstr ""D"" IL_00a9: call ""bool string.op_Equality(string, string)"" IL_00ae: brtrue.s IL_0113 IL_00b0: ret IL_00b1: ldloc.0 IL_00b2: ldstr ""E"" IL_00b7: call ""bool string.op_Equality(string, string)"" IL_00bc: brtrue.s IL_011a IL_00be: ret IL_00bf: ldloc.0 IL_00c0: ldstr ""F"" IL_00c5: call ""bool string.op_Equality(string, string)"" IL_00ca: brtrue.s IL_0121 IL_00cc: ret IL_00cd: ldloc.0 IL_00ce: ldstr ""G"" IL_00d3: call ""bool string.op_Equality(string, string)"" IL_00d8: brtrue.s IL_0128 IL_00da: ret IL_00db: ldloc.0 IL_00dc: ldstr ""H"" IL_00e1: call ""bool string.op_Equality(string, string)"" IL_00e6: brtrue.s IL_012f IL_00e8: ret IL_00e9: ldloc.0 IL_00ea: ldstr ""I"" IL_00ef: call ""bool string.op_Equality(string, string)"" IL_00f4: brtrue.s IL_0136 IL_00f6: ret IL_00f7: ldloc.0 IL_00f8: ldstr ""J"" IL_00fd: call ""bool string.op_Equality(string, string)"" IL_0102: brtrue.s IL_013e IL_0104: ret IL_0105: ldc.i4.2 IL_0106: call ""void System.Console.Write(int)"" IL_010b: ret IL_010c: ldc.i4.3 IL_010d: call ""void System.Console.Write(int)"" IL_0112: ret IL_0113: ldc.i4.4 IL_0114: call ""void System.Console.Write(int)"" IL_0119: ret IL_011a: ldc.i4.5 IL_011b: call ""void System.Console.Write(int)"" IL_0120: ret IL_0121: ldc.i4.6 IL_0122: call ""void System.Console.Write(int)"" IL_0127: ret IL_0128: ldc.i4.7 IL_0129: call ""void System.Console.Write(int)"" IL_012e: ret IL_012f: ldc.i4.8 IL_0130: call ""void System.Console.Write(int)"" IL_0135: ret IL_0136: ldc.i4.s 9 IL_0138: call ""void System.Console.Write(int)"" IL_013d: ret IL_013e: ldc.i4.s 10 IL_0140: call ""void System.Console.Write(int)"" IL_0145: ret }"); } [WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")] [WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")] [Fact] public void LargeStringSwitchWithoutStringChars() { var text = @" using System; public class Test { public static void Main(string [] args) { switch(args[0]) { case ""A"": Console.Write(1); break; case ""B"": Console.Write(2); break; case ""C"": Console.Write(3); break; case ""D"": Console.Write(4); break; case ""E"": Console.Write(5); break; case ""F"": Console.Write(6); break; case ""G"": Console.Write(7); break; case ""H"": Console.Write(8); break; case ""I"": Console.Write(9); break; } } }"; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE")); // With special members available, we use a hashtable approach. CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 307 (0x133) .maxstack 2 .locals init (string V_0, uint V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""ComputeStringHash"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: ldc.i4 0xc30bf539 IL_0011: bgt.un.s IL_0043 IL_0013: ldloc.1 IL_0014: ldc.i4 0xc10bf213 IL_0019: bgt.un.s IL_002f IL_001b: ldloc.1 IL_001c: ldc.i4 0xc00bf080 IL_0021: beq IL_00ad IL_0026: ldloc.1 IL_0027: ldc.i4 0xc10bf213 IL_002c: beq.s IL_009f IL_002e: ret IL_002f: ldloc.1 IL_0030: ldc.i4 0xc20bf3a6 IL_0035: beq IL_00c9 IL_003a: ldloc.1 IL_003b: ldc.i4 0xc30bf539 IL_0040: beq.s IL_00bb IL_0042: ret IL_0043: ldloc.1 IL_0044: ldc.i4 0xc60bf9f2 IL_0049: bgt.un.s IL_005c IL_004b: ldloc.1 IL_004c: ldc.i4 0xc40bf6cc IL_0051: beq.s IL_0075 IL_0053: ldloc.1 IL_0054: ldc.i4 0xc60bf9f2 IL_0059: beq.s IL_0091 IL_005b: ret IL_005c: ldloc.1 IL_005d: ldc.i4 0xc70bfb85 IL_0062: beq.s IL_0083 IL_0064: ldloc.1 IL_0065: ldc.i4 0xcc0c0364 IL_006a: beq.s IL_00e5 IL_006c: ldloc.1 IL_006d: ldc.i4 0xcd0c04f7 IL_0072: beq.s IL_00d7 IL_0074: ret IL_0075: ldloc.0 IL_0076: ldstr ""A"" IL_007b: call ""bool string.op_Equality(string, string)"" IL_0080: brtrue.s IL_00f3 IL_0082: ret IL_0083: ldloc.0 IL_0084: ldstr ""B"" IL_0089: call ""bool string.op_Equality(string, string)"" IL_008e: brtrue.s IL_00fa IL_0090: ret IL_0091: ldloc.0 IL_0092: ldstr ""C"" IL_0097: call ""bool string.op_Equality(string, string)"" IL_009c: brtrue.s IL_0101 IL_009e: ret IL_009f: ldloc.0 IL_00a0: ldstr ""D"" IL_00a5: call ""bool string.op_Equality(string, string)"" IL_00aa: brtrue.s IL_0108 IL_00ac: ret IL_00ad: ldloc.0 IL_00ae: ldstr ""E"" IL_00b3: call ""bool string.op_Equality(string, string)"" IL_00b8: brtrue.s IL_010f IL_00ba: ret IL_00bb: ldloc.0 IL_00bc: ldstr ""F"" IL_00c1: call ""bool string.op_Equality(string, string)"" IL_00c6: brtrue.s IL_0116 IL_00c8: ret IL_00c9: ldloc.0 IL_00ca: ldstr ""G"" IL_00cf: call ""bool string.op_Equality(string, string)"" IL_00d4: brtrue.s IL_011d IL_00d6: ret IL_00d7: ldloc.0 IL_00d8: ldstr ""H"" IL_00dd: call ""bool string.op_Equality(string, string)"" IL_00e2: brtrue.s IL_0124 IL_00e4: ret IL_00e5: ldloc.0 IL_00e6: ldstr ""I"" IL_00eb: call ""bool string.op_Equality(string, string)"" IL_00f0: brtrue.s IL_012b IL_00f2: ret IL_00f3: ldc.i4.1 IL_00f4: call ""void System.Console.Write(int)"" IL_00f9: ret IL_00fa: ldc.i4.2 IL_00fb: call ""void System.Console.Write(int)"" IL_0100: ret IL_0101: ldc.i4.3 IL_0102: call ""void System.Console.Write(int)"" IL_0107: ret IL_0108: ldc.i4.4 IL_0109: call ""void System.Console.Write(int)"" IL_010e: ret IL_010f: ldc.i4.5 IL_0110: call ""void System.Console.Write(int)"" IL_0115: ret IL_0116: ldc.i4.6 IL_0117: call ""void System.Console.Write(int)"" IL_011c: ret IL_011d: ldc.i4.7 IL_011e: call ""void System.Console.Write(int)"" IL_0123: ret IL_0124: ldc.i4.8 IL_0125: call ""void System.Console.Write(int)"" IL_012a: ret IL_012b: ldc.i4.s 9 IL_012d: call ""void System.Console.Write(int)"" IL_0132: ret }"); comp = CreateCompilation(text); comp.MakeMemberMissing(SpecialMember.System_String__Chars); // Can't use the hash version when String.Chars is unavailable. CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 186 (0xba) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldstr ""A"" IL_000a: call ""bool string.op_Equality(string, string)"" IL_000f: brtrue.s IL_007a IL_0011: ldloc.0 IL_0012: ldstr ""B"" IL_0017: call ""bool string.op_Equality(string, string)"" IL_001c: brtrue.s IL_0081 IL_001e: ldloc.0 IL_001f: ldstr ""C"" IL_0024: call ""bool string.op_Equality(string, string)"" IL_0029: brtrue.s IL_0088 IL_002b: ldloc.0 IL_002c: ldstr ""D"" IL_0031: call ""bool string.op_Equality(string, string)"" IL_0036: brtrue.s IL_008f IL_0038: ldloc.0 IL_0039: ldstr ""E"" IL_003e: call ""bool string.op_Equality(string, string)"" IL_0043: brtrue.s IL_0096 IL_0045: ldloc.0 IL_0046: ldstr ""F"" IL_004b: call ""bool string.op_Equality(string, string)"" IL_0050: brtrue.s IL_009d IL_0052: ldloc.0 IL_0053: ldstr ""G"" IL_0058: call ""bool string.op_Equality(string, string)"" IL_005d: brtrue.s IL_00a4 IL_005f: ldloc.0 IL_0060: ldstr ""H"" IL_0065: call ""bool string.op_Equality(string, string)"" IL_006a: brtrue.s IL_00ab IL_006c: ldloc.0 IL_006d: ldstr ""I"" IL_0072: call ""bool string.op_Equality(string, string)"" IL_0077: brtrue.s IL_00b2 IL_0079: ret IL_007a: ldc.i4.1 IL_007b: call ""void System.Console.Write(int)"" IL_0080: ret IL_0081: ldc.i4.2 IL_0082: call ""void System.Console.Write(int)"" IL_0087: ret IL_0088: ldc.i4.3 IL_0089: call ""void System.Console.Write(int)"" IL_008e: ret IL_008f: ldc.i4.4 IL_0090: call ""void System.Console.Write(int)"" IL_0095: ret IL_0096: ldc.i4.5 IL_0097: call ""void System.Console.Write(int)"" IL_009c: ret IL_009d: ldc.i4.6 IL_009e: call ""void System.Console.Write(int)"" IL_00a3: ret IL_00a4: ldc.i4.7 IL_00a5: call ""void System.Console.Write(int)"" IL_00aa: ret IL_00ab: ldc.i4.8 IL_00ac: call ""void System.Console.Write(int)"" IL_00b1: ret IL_00b2: ldc.i4.s 9 IL_00b4: call ""void System.Console.Write(int)"" IL_00b9: ret }"); } [WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")] [Fact] public void Regress947580() { var text = @" using System; class Program { static string boo(int i) { switch (i) { case 42: var x = ""goo""; if (x != ""bar"") break; return x; } return null; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //x IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_001a IL_0005: ldstr ""goo"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""bar"" IL_0011: call ""bool string.op_Inequality(string, string)"" IL_0016: brtrue.s IL_001a IL_0018: ldloc.0 IL_0019: ret IL_001a: ldnull IL_001b: ret }" ); } [WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")] [Fact] public void Regress947580a() { var text = @" using System; class Program { static string boo(int i) { switch (i) { case 42: var x = ""goo""; if (x != ""bar"") break; break; } return null; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_0015 IL_0005: ldstr ""goo"" IL_000a: ldstr ""bar"" IL_000f: call ""bool string.op_Inequality(string, string)"" IL_0014: pop IL_0015: ldnull IL_0016: ret }" ); } [WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")] [Fact] public void Regress1035228() { var text = @" using System; class Program { static bool boo(int i) { var ii = i; switch (++ii) { case 42: var x = ""goo""; if (x != ""bar"") { return false; } break; } return true; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: add IL_0003: ldc.i4.s 42 IL_0005: bne.un.s IL_001a IL_0007: ldstr ""goo"" IL_000c: ldstr ""bar"" IL_0011: call ""bool string.op_Inequality(string, string)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.0 IL_0019: ret IL_001a: ldc.i4.1 IL_001b: ret }" ); } [WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")] [Fact] public void Regress1035228a() { var text = @" using System; class Program { static bool boo(int i) { var ii = i; switch (ii++) { case 42: var x = ""goo""; if (x != ""bar"") { return false; } break; } return true; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_0018 IL_0005: ldstr ""goo"" IL_000a: ldstr ""bar"" IL_000f: call ""bool string.op_Inequality(string, string)"" IL_0014: brfalse.s IL_0018 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldc.i4.1 IL_0019: ret }" ); } [WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")] [Fact] public void Regress4701() { var text = @" using System; namespace ConsoleApplication1 { class Program { private void SwtchTest() { int? i; i = 1; switch (i) { case null: Console.WriteLine(""In Null case""); i = 1; break; default: Console.WriteLine(""In DEFAULT case""); i = i + 2; break; } } static void Main(string[] args) { var p = new Program(); p.SwtchTest(); } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case"); compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest", @" { // Code size 84 (0x54) .maxstack 2 .locals init (int? V_0, //i int? V_1, int? V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""int?..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""bool int?.HasValue.get"" IL_000f: brtrue.s IL_0024 IL_0011: ldstr ""In Null case"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.1 IL_001e: call ""int?..ctor(int)"" IL_0023: ret IL_0024: ldstr ""In DEFAULT case"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ldloc.0 IL_002f: stloc.1 IL_0030: ldloca.s V_1 IL_0032: call ""bool int?.HasValue.get"" IL_0037: brtrue.s IL_0044 IL_0039: ldloca.s V_2 IL_003b: initobj ""int?"" IL_0041: ldloc.2 IL_0042: br.s IL_0052 IL_0044: ldloca.s V_1 IL_0046: call ""int int?.GetValueOrDefault()"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: newobj ""int?..ctor(int)"" IL_0052: stloc.0 IL_0053: ret }" ); } [WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")] [Fact] public void Regress4701a() { var text = @" using System; namespace ConsoleApplication1 { class Program { private void SwtchTest() { string i = null; i = ""1""; switch (i) { case null: Console.WriteLine(""In Null case""); break; default: Console.WriteLine(""In DEFAULT case""); break; } } static void Main(string[] args) { var p = new Program(); p.SwtchTest(); } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case"); compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldstr ""1"" IL_0005: brtrue.s IL_0012 IL_0007: ldstr ""In Null case"" IL_000c: call ""void System.Console.WriteLine(string)"" IL_0011: ret IL_0012: ldstr ""In DEFAULT case"" IL_0017: call ""void System.Console.WriteLine(string)"" IL_001c: ret }" ); } #endregion #region regression tests [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_01() { var source = @"using System; public class Program { public static void Main() { switch (StringSplitOptions.RemoveEmptyEntries) { case object o: Console.WriteLine(o); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""System.StringSplitOptions"" IL_0006: call ""void System.Console.WriteLine(object)"" IL_000b: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 26 (0x1a) .maxstack 1 .locals init (object V_0, //o System.StringSplitOptions V_1, System.StringSplitOptions V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldc.i4.1 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""System.StringSplitOptions"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: call ""void System.Console.WriteLine(object)"" IL_0016: nop IL_0017: br.s IL_0019 IL_0019: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void ExplicitNullablePatternSwitch_02() { var source = @"using System; public class Program { public static void Main() { M(null); M(1); } public static void M(int? x) { switch (x) { case int i: // explicit nullable conversion Console.Write(i); break; case null: Console.Write(""null""); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "null1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 33 (0x21) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldstr ""null"" IL_001b: call ""void System.Console.Write(string)"" IL_0020: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "null1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (int V_0, //i int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloca.s V_1 IL_0007: call ""bool int?.HasValue.get"" IL_000c: brfalse.s IL_0023 IL_000e: ldloca.s V_1 IL_0010: call ""int int?.GetValueOrDefault()"" IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: br.s IL_001a IL_001a: ldloc.0 IL_001b: call ""void System.Console.Write(int)"" IL_0020: nop IL_0021: br.s IL_0030 IL_0023: ldstr ""null"" IL_0028: call ""void System.Console.Write(string)"" IL_002d: nop IL_002e: br.s IL_0030 IL_0030: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_04() { var source = @"using System; public class Program { public static void Main() { M(1); } public static void M(int x) { switch (x) { case System.IComparable i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""int"" IL_0006: call ""void System.Console.Write(object)"" IL_000b: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 26 (0x1a) .maxstack 1 .locals init (System.IComparable V_0, //i int V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""int"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: call ""void System.Console.Write(object)"" IL_0016: nop IL_0017: br.s IL_0019 IL_0019: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_05() { var source = @"using System; public class Program { public static void Main() { M(1); M(null); } public static void M(int? x) { switch (x) { case System.IComparable i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 17 (0x11) .maxstack 1 .locals init (System.IComparable V_0) //i IL_0000: ldarg.0 IL_0001: box ""int?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: call ""void System.Console.Write(object)"" IL_0010: ret } " ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (System.IComparable V_0, //i int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""int?"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_001c IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: call ""void System.Console.Write(object)"" IL_0019: nop IL_001a: br.s IL_001c IL_001c: ret } " ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_06() { var source = @"using System; public class Program { public static void Main() { M(1); M(null); M(nameof(Main)); } public static void M(object x) { switch (x) { case int i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brfalse.s IL_0013 IL_0008: ldarg.0 IL_0009: unbox.any ""int"" IL_000e: call ""void System.Console.Write(int)"" IL_0013: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 34 (0x22) .maxstack 1 .locals init (int V_0, //i object V_1, object V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldloc.1 IL_000e: unbox.any ""int"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: call ""void System.Console.Write(int)"" IL_001e: nop IL_001f: br.s IL_0021 IL_0021: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_07() { var source = @"using System; public class Program { public static void Main() { M<int>(1); M<int>(null); M<int>(10.5); } public static void M<T>(object x) { // when T is not known to be a reference type, there is an unboxing conversion from // the effective base class C of T to T and from any base class of C to T. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0018 IL_0008: ldarg.0 IL_0009: unbox.any ""T"" IL_000e: box ""T"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 39 (0x27) .maxstack 1 .locals init (T V_0, //i object V_1, object V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0026 IL_000d: ldloc.1 IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: box ""T"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: nop IL_0024: br.s IL_0026 IL_0026: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_08() { var source = @"using System; public class Program { public static void Main() { M<int>(1); M<int>(null); M<int>(10.5); } public static void M<T>(IComparable x) { // when T is not known to be a reference type, there is an unboxing conversion from // any interface type to T. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0018 IL_0008: ldarg.0 IL_0009: unbox.any ""T"" IL_000e: box ""T"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 39 (0x27) .maxstack 1 .locals init (T V_0, //i System.IComparable V_1, System.IComparable V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0026 IL_000d: ldloc.1 IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: box ""T"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: nop IL_0024: br.s IL_0026 IL_0026: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnoxInPatternSwitch_09() { var source = @"using System; public class Program { public static void Main() { M<int, object>(1); M<int, object>(null); M<int, object>(10.5); } public static void M<T, U>(U x) where T : U { // when T is not known to be a reference type, there is an unboxing conversion from // a type parameter U to T, provided T depends on U. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T, U>", @"{ // Code size 35 (0x23) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""U"" IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0022 IL_000d: ldarg.0 IL_000e: box ""U"" IL_0013: unbox.any ""T"" IL_0018: box ""T"" IL_001d: call ""void System.Console.Write(object)"" IL_0022: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T, U>", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (T V_0, //i U V_1, U V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""U"" IL_000b: isinst ""T"" IL_0010: brfalse.s IL_0030 IL_0012: ldloc.1 IL_0013: box ""U"" IL_0018: unbox.any ""T"" IL_001d: stloc.0 IL_001e: br.s IL_0020 IL_0020: br.s IL_0022 IL_0022: ldloc.0 IL_0023: box ""T"" IL_0028: call ""void System.Console.Write(object)"" IL_002d: nop IL_002e: br.s IL_0030 IL_0030: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternIf_02() { var source = @"using System; public class Program { public static void Main() { if (StringSplitOptions.RemoveEmptyEntries is object o) { Console.WriteLine(o); } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 14 (0xe) .maxstack 1 .locals init (object V_0) //o IL_0000: ldc.i4.1 IL_0001: box ""System.StringSplitOptions"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (object V_0, //o bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""System.StringSplitOptions"" IL_0007: stloc.0 IL_0008: ldc.i4.1 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: brfalse.s IL_0016 IL_000d: nop IL_000e: ldloc.0 IL_000f: call ""void System.Console.WriteLine(object)"" IL_0014: nop IL_0015: nop IL_0016: ret }" ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_01() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<int>(2)); Console.Write(M2<int>(3)); Console.Write(M1<int>(1.1)); Console.Write(M2<int>(1.1)); } public static T M1<T>(ValueType o) { return o is T t ? t : default(T); } public static T M2<T>(ValueType o) { switch (o) { case T t: return t; default: return default(T); } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(19, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 34 (0x22) .maxstack 1 .locals init (T V_0, //t T V_1) IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0016 IL_0008: ldarg.0 IL_0009: isinst ""T"" IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0020 IL_0016: ldloca.s V_1 IL_0018: initobj ""T"" IL_001e: ldloc.1 IL_001f: ret IL_0020: ldloc.0 IL_0021: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 40 (0x28) .maxstack 1 .locals init (T V_0, //t T V_1, T V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""T"" IL_0007: brfalse.s IL_0017 IL_0009: ldarg.0 IL_000a: isinst ""T"" IL_000f: unbox.any ""T"" IL_0014: stloc.0 IL_0015: br.s IL_0022 IL_0017: ldloca.s V_1 IL_0019: initobj ""T"" IL_001f: ldloc.1 IL_0020: br.s IL_0023 IL_0022: ldloc.0 IL_0023: stloc.2 IL_0024: br.s IL_0026 IL_0026: ldloc.2 IL_0027: ret }" ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 48 (0x30) .maxstack 1 .locals init (T V_0, //t System.ValueType V_1, System.ValueType V_2, T V_3, T V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0021 IL_000d: ldloc.1 IL_000e: isinst ""T"" IL_0013: unbox.any ""T"" IL_0018: stloc.0 IL_0019: br.s IL_001b IL_001b: br.s IL_001d IL_001d: ldloc.0 IL_001e: stloc.3 IL_001f: br.s IL_002e IL_0021: ldloca.s V_4 IL_0023: initobj ""T"" IL_0029: ldloc.s V_4 IL_002b: stloc.3 IL_002c: br.s IL_002e IL_002e: ldloc.3 IL_002f: ret }" ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_02() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1(2)); Console.Write(M2(3)); Console.Write(M1(1.1)); Console.Write(M2(1.1)); } public static int M1<T>(T o) { return o is int t ? t : default(int); } public static int M2<T>(T o) { switch (o) { case int t: return t; default: return default(int); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater. // return o is int t ? t : default(int); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater. // case int t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(19, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 36 (0x24) .maxstack 1 .locals init (int V_0) //t IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0020 IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: stloc.0 IL_001e: br.s IL_0022 IL_0020: ldc.i4.0 IL_0021: ret IL_0022: ldloc.0 IL_0023: ret } " ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 32 (0x20) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_001e IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ret IL_001e: ldc.i4.0 IL_001f: ret } " ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 42 (0x2a) .maxstack 1 .locals init (int V_0, //t int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: isinst ""int"" IL_000c: brfalse.s IL_0021 IL_000e: ldarg.0 IL_000f: box ""T"" IL_0014: isinst ""int"" IL_0019: unbox.any ""int"" IL_001e: stloc.0 IL_001f: br.s IL_0024 IL_0021: ldc.i4.0 IL_0022: br.s IL_0025 IL_0024: ldloc.0 IL_0025: stloc.1 IL_0026: br.s IL_0028 IL_0028: ldloc.1 IL_0029: ret } " ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (int V_0, //t T V_1, T V_2, int V_3) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""T"" IL_000b: isinst ""int"" IL_0010: brfalse.s IL_002b IL_0012: ldloc.1 IL_0013: box ""T"" IL_0018: isinst ""int"" IL_001d: unbox.any ""int"" IL_0022: stloc.0 IL_0023: br.s IL_0025 IL_0025: br.s IL_0027 IL_0027: ldloc.0 IL_0028: stloc.3 IL_0029: br.s IL_002f IL_002b: ldc.i4.0 IL_002c: stloc.3 IL_002d: br.s IL_002f IL_002f: ldloc.3 IL_0030: ret } " ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_03() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<int>(2)); Console.Write(M2<int>(3)); Console.Write(M1<int>(1.1)); Console.Write(M2<int>(1.1)); } public static T M1<T>(ValueType o) where T : struct { return o is T t ? t : default(T); } public static T M2<T>(ValueType o) where T : struct { switch (o) { case T t: return t; default: return default(T); } } } "; var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "2300"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_04() { var source = @"using System; class Program { public static void Main(string[] args) { var x = new X(); Console.Write(M1<B>(new A()) ?? x); Console.Write(M2<B>(new A()) ?? x); Console.Write(M1<B>(new B()) ?? x); Console.Write(M2<B>(new B()) ?? x); } public static T M1<T>(A o) where T : class { return o is T t ? t : default(T); } public static T M2<T>(A o) where T : class { switch (o) { case T t: return t; default: return default(T); } } } class A { } class B : A { } class X : B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21), // (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "XXBB"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_05() { var source = @"using System; class Program { public static void Main(string[] args) { var x = new X(); Console.Write(M1<B>(new A()) ?? x); Console.Write(M2<B>(new A()) ?? x); Console.Write(M1<B>(new B()) ?? x); Console.Write(M2<B>(new B()) ?? x); } public static T M1<T>(A o) where T : I1 { return o is T t ? t : default(T); } public static T M2<T>(A o) where T : I1 { switch (o) { case T t: return t; default: return default(T); } } } interface I1 { } class A : I1 { } class B : A { } class X : B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21), // (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "XXBB"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_06() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<B>(new A())); Console.Write(M2<B>(new A())); Console.Write(M1<A>(new A())); Console.Write(M2<A>(new A())); } public static bool M1<T>(A o) where T : I1 { return o is T t; } public static bool M2<T>(A o) where T : I1 { switch (o) { case T t: return true; default: return false; } } } interface I1 { } struct A : I1 { } struct B : I1 { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18) ); var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "FalseFalseTrueTrue"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_07() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<B>(new A())); Console.Write(M2<B>(new A())); Console.Write(M1<A>(new A())); Console.Write(M2<A>(new A())); } public static bool M1<T>(A o) where T : new() { return o is T t; } public static bool M2<T>(A o) where T : new() { switch (o) { case T t: return true; default: return false; } } } struct A { } struct B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18) ); var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "FalseFalseTrueTrue"); compVerifier.VerifyDiagnostics(); } [Fact] [WorkItem(16195, "https://github.com/dotnet/roslyn/issues/31269")] public void TestIgnoreDynamicVsObjectAndTupleElementNames_01() { var source = @"public class Generic<T> { public enum Color { Red=1, Blue=2 } } class Program { public static void Main(string[] args) { } public static void M2(object o) { switch (o) { case Generic<long>.Color c: case Generic<object>.Color.Red: case Generic<(int x, int y)>.Color.Blue: case Generic<string>.Color.Red: case Generic<dynamic>.Color.Red: // error: duplicate case case Generic<(int z, int w)>.Color.Blue: // error: duplicate case case Generic<(int z, long w)>.Color.Blue: default: break; } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case Generic<dynamic>.Color.Red: // error: duplicate case Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<dynamic>.Color.Red:").WithArguments("1").WithLocation(18, 13), // (19,13): error CS0152: The switch statement contains multiple cases with the label value '2' // case Generic<(int z, int w)>.Color.Blue: // error: duplicate case Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<(int z, int w)>.Color.Blue:").WithArguments("2").WithLocation(19, 13) ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestIgnoreDynamicVsObjectAndTupleElementNames_02() { var source = @"using System; public class Generic<T> { public enum Color { X0, X1, X2, Green, Blue, Red } } class Program { public static void Main(string[] args) { Console.WriteLine(M1<Generic<int>.Color>(Generic<long>.Color.Red)); // False Console.WriteLine(M1<Generic<string>.Color>(Generic<object>.Color.Red)); // False Console.WriteLine(M1<Generic<(int x, int y)>.Color>(Generic<(int z, int w)>.Color.Red)); // True Console.WriteLine(M1<Generic<object>.Color>(Generic<dynamic>.Color.Blue)); // True Console.WriteLine(M2(Generic<long>.Color.Red)); // Generic<long>.Color.Red Console.WriteLine(M2(Generic<object>.Color.Blue)); // Generic<dynamic>.Color.Blue Console.WriteLine(M2(Generic<int>.Color.Red)); // None Console.WriteLine(M2(Generic<dynamic>.Color.Red)); // Generic<object>.Color.Red } public static bool M1<T>(object o) { return o is T t; } public static string M2(object o) { switch (o) { case Generic<long>.Color c: return ""Generic<long>.Color."" + c; case Generic<object>.Color.Red: return ""Generic<object>.Color.Red""; case Generic<dynamic>.Color.Blue: return ""Generic<dynamic>.Color.Blue""; default: return ""None""; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: @"False False True True Generic<long>.Color.Red Generic<dynamic>.Color.Blue None Generic<object>.Color.Red"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (Generic<long>.Color V_0, //c object V_1, Generic<object>.Color V_2, object V_3, string V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""Generic<long>.Color"" IL_000b: brfalse.s IL_0016 IL_000d: ldloc.1 IL_000e: unbox.any ""Generic<long>.Color"" IL_0013: stloc.0 IL_0014: br.s IL_0031 IL_0016: ldloc.1 IL_0017: isinst ""Generic<object>.Color"" IL_001c: brfalse.s IL_0060 IL_001e: ldloc.1 IL_001f: unbox.any ""Generic<object>.Color"" IL_0024: stloc.2 IL_0025: ldloc.2 IL_0026: ldc.i4.4 IL_0027: beq.s IL_0057 IL_0029: br.s IL_002b IL_002b: ldloc.2 IL_002c: ldc.i4.5 IL_002d: beq.s IL_004e IL_002f: br.s IL_0060 IL_0031: br.s IL_0033 IL_0033: ldstr ""Generic<long>.Color."" IL_0038: ldloca.s V_0 IL_003a: constrained. ""Generic<long>.Color"" IL_0040: callvirt ""string object.ToString()"" IL_0045: call ""string string.Concat(string, string)"" IL_004a: stloc.s V_4 IL_004c: br.s IL_0069 IL_004e: ldstr ""Generic<object>.Color.Red"" IL_0053: stloc.s V_4 IL_0055: br.s IL_0069 IL_0057: ldstr ""Generic<dynamic>.Color.Blue"" IL_005c: stloc.s V_4 IL_005e: br.s IL_0069 IL_0060: ldstr ""None"" IL_0065: stloc.s V_4 IL_0067: br.s IL_0069 IL_0069: ldloc.s V_4 IL_006b: ret } " ); } [Fact, WorkItem(16129, "https://github.com/dotnet/roslyn/issues/16129")] public void ExactPatternMatch() { var source = @"using System; class C { static void Main() { if (TrySomething() is ValueTuple<string, bool> v && v.Item2) { System.Console.Write(v.Item1 == null); } } static (string Value, bool Success) TrySomething() { return (null, true); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: @"True"); compVerifier.VerifyIL("C.Main", @"{ // Code size 29 (0x1d) .maxstack 2 .locals init (System.ValueTuple<string, bool> V_0) //v IL_0000: call ""System.ValueTuple<string, bool> C.TrySomething()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_000c: brfalse.s IL_001c IL_000e: ldloc.0 IL_000f: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_0014: ldnull IL_0015: ceq IL_0017: call ""void System.Console.Write(bool)"" IL_001c: ret }" ); } [WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ShareLikeKindedTemps_01() { var source = @"using System; public class Program { public static void Main() { } static bool b = false; public static void M(object o) { switch (o) { case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: ""); compVerifier.VerifyIL("Program.M", @" { // Code size 120 (0x78) .maxstack 2 .locals init (int V_0, int V_1, //i object V_2) IL_0000: ldarg.0 IL_0001: stloc.2 IL_0002: ldloc.2 IL_0003: isinst ""int"" IL_0008: brfalse.s IL_001c IL_000a: ldloc.2 IL_000b: unbox.any ""int"" IL_0010: stloc.1 IL_0011: ldsfld ""bool Program.b"" IL_0016: brtrue.s IL_0077 IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: br.s IL_001e IL_001c: ldc.i4.7 IL_001d: stloc.0 IL_001e: ldsfld ""bool Program.b"" IL_0023: brtrue.s IL_0077 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: beq.s IL_002e IL_0029: ldloc.0 IL_002a: ldc.i4.7 IL_002b: beq.s IL_0039 IL_002d: ret IL_002e: ldsfld ""bool Program.b"" IL_0033: brtrue.s IL_0077 IL_0035: ldc.i4.3 IL_0036: stloc.0 IL_0037: br.s IL_003b IL_0039: ldc.i4.8 IL_003a: stloc.0 IL_003b: ldsfld ""bool Program.b"" IL_0040: brtrue.s IL_0077 IL_0042: ldloc.0 IL_0043: ldc.i4.3 IL_0044: beq.s IL_004b IL_0046: ldloc.0 IL_0047: ldc.i4.8 IL_0048: beq.s IL_0056 IL_004a: ret IL_004b: ldsfld ""bool Program.b"" IL_0050: brtrue.s IL_0077 IL_0052: ldc.i4.5 IL_0053: stloc.0 IL_0054: br.s IL_0059 IL_0056: ldc.i4.s 9 IL_0058: stloc.0 IL_0059: ldsfld ""bool Program.b"" IL_005e: brtrue.s IL_0077 IL_0060: ldloc.0 IL_0061: ldc.i4.5 IL_0062: beq.s IL_006a IL_0064: ldloc.0 IL_0065: ldc.i4.s 9 IL_0067: beq.s IL_0071 IL_0069: ret IL_006a: ldsfld ""bool Program.b"" IL_006f: brtrue.s IL_0077 IL_0071: ldsfld ""bool Program.b"" IL_0076: pop IL_0077: ret }" ); compVerifier = CompileAndVerify(source, expectedOutput: "", symbolValidator: validator, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication).WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("Program"); Assert.Null(type.GetMember(".cctor")); } compVerifier.VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source, expectedIL: @"{ // Code size 194 (0xc2) .maxstack 2 .locals init (int V_0, int V_1, //i int V_2, //i int V_3, //i int V_4, //i object V_5, object V_6) // sequence point: { IL_0000: nop // sequence point: switch (o) IL_0001: ldarg.0 IL_0002: stloc.s V_6 // sequence point: <hidden> IL_0004: ldloc.s V_6 IL_0006: stloc.s V_5 // sequence point: <hidden> IL_0008: ldloc.s V_5 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_002d IL_0011: ldloc.s V_5 IL_0013: unbox.any ""int"" IL_0018: stloc.1 // sequence point: <hidden> IL_0019: br.s IL_001b // sequence point: when b IL_001b: ldsfld ""bool Program.b"" IL_0020: brtrue.s IL_0024 // sequence point: <hidden> IL_0022: br.s IL_0029 // sequence point: break; IL_0024: br IL_00c1 // sequence point: <hidden> IL_0029: ldc.i4.1 IL_002a: stloc.0 IL_002b: br.s IL_0031 IL_002d: ldc.i4.7 IL_002e: stloc.0 IL_002f: br.s IL_0031 // sequence point: when b IL_0031: ldsfld ""bool Program.b"" IL_0036: brtrue.s IL_0048 // sequence point: <hidden> IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: beq.s IL_0044 IL_003c: br.s IL_003e IL_003e: ldloc.0 IL_003f: ldc.i4.7 IL_0040: beq.s IL_0046 IL_0042: br.s IL_0048 IL_0044: br.s IL_004a IL_0046: br.s IL_005b // sequence point: break; IL_0048: br.s IL_00c1 // sequence point: <hidden> IL_004a: ldloc.1 IL_004b: stloc.2 // sequence point: when b IL_004c: ldsfld ""bool Program.b"" IL_0051: brtrue.s IL_0055 // sequence point: <hidden> IL_0053: br.s IL_0057 // sequence point: break; IL_0055: br.s IL_00c1 // sequence point: <hidden> IL_0057: ldc.i4.3 IL_0058: stloc.0 IL_0059: br.s IL_005f IL_005b: ldc.i4.8 IL_005c: stloc.0 IL_005d: br.s IL_005f // sequence point: when b IL_005f: ldsfld ""bool Program.b"" IL_0064: brtrue.s IL_0076 // sequence point: <hidden> IL_0066: ldloc.0 IL_0067: ldc.i4.3 IL_0068: beq.s IL_0072 IL_006a: br.s IL_006c IL_006c: ldloc.0 IL_006d: ldc.i4.8 IL_006e: beq.s IL_0074 IL_0070: br.s IL_0076 IL_0072: br.s IL_0078 IL_0074: br.s IL_0089 // sequence point: break; IL_0076: br.s IL_00c1 // sequence point: <hidden> IL_0078: ldloc.1 IL_0079: stloc.3 // sequence point: when b IL_007a: ldsfld ""bool Program.b"" IL_007f: brtrue.s IL_0083 // sequence point: <hidden> IL_0081: br.s IL_0085 // sequence point: break; IL_0083: br.s IL_00c1 // sequence point: <hidden> IL_0085: ldc.i4.5 IL_0086: stloc.0 IL_0087: br.s IL_008e IL_0089: ldc.i4.s 9 IL_008b: stloc.0 IL_008c: br.s IL_008e // sequence point: when b IL_008e: ldsfld ""bool Program.b"" IL_0093: brtrue.s IL_00a6 // sequence point: <hidden> IL_0095: ldloc.0 IL_0096: ldc.i4.5 IL_0097: beq.s IL_00a2 IL_0099: br.s IL_009b IL_009b: ldloc.0 IL_009c: ldc.i4.s 9 IL_009e: beq.s IL_00a4 IL_00a0: br.s IL_00a6 IL_00a2: br.s IL_00a8 IL_00a4: br.s IL_00b6 // sequence point: break; IL_00a6: br.s IL_00c1 // sequence point: <hidden> IL_00a8: ldloc.1 IL_00a9: stloc.s V_4 // sequence point: when b IL_00ab: ldsfld ""bool Program.b"" IL_00b0: brtrue.s IL_00b4 // sequence point: <hidden> IL_00b2: br.s IL_00b6 // sequence point: break; IL_00b4: br.s IL_00c1 // sequence point: when b IL_00b6: ldsfld ""bool Program.b"" IL_00bb: brtrue.s IL_00bf // sequence point: <hidden> IL_00bd: br.s IL_00c1 // sequence point: break; IL_00bf: br.s IL_00c1 // sequence point: } IL_00c1: ret }" ); compVerifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""Program"" methodName=""Main"" /> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method containingType=""Program"" name=""M"" parameterNames=""o""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""0"" offset=""55"" /> <slot kind=""0"" offset=""133"" /> <slot kind=""0"" offset=""211"" /> <slot kind=""0"" offset=""289"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""38"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""13"" startColumn=""24"" endLine=""13"" endColumn=""30"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""32"" endLine=""13"" endColumn=""38"" document=""1"" /> <entry offset=""0x4a"" hidden=""true"" document=""1"" /> <entry offset=""0x4c"" startLine=""14"" startColumn=""24"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x53"" hidden=""true"" document=""1"" /> <entry offset=""0x55"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""38"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x5f"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""30"" document=""1"" /> <entry offset=""0x66"" hidden=""true"" document=""1"" /> <entry offset=""0x76"" startLine=""15"" startColumn=""32"" endLine=""15"" endColumn=""38"" document=""1"" /> <entry offset=""0x78"" hidden=""true"" document=""1"" /> <entry offset=""0x7a"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x81"" hidden=""true"" document=""1"" /> <entry offset=""0x83"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""38"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""17"" startColumn=""24"" endLine=""17"" endColumn=""30"" document=""1"" /> <entry offset=""0x95"" hidden=""true"" document=""1"" /> <entry offset=""0xa6"" startLine=""17"" startColumn=""32"" endLine=""17"" endColumn=""38"" document=""1"" /> <entry offset=""0xa8"" hidden=""true"" document=""1"" /> <entry offset=""0xab"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""30"" document=""1"" /> <entry offset=""0xb2"" hidden=""true"" document=""1"" /> <entry offset=""0xb4"" startLine=""18"" startColumn=""32"" endLine=""18"" endColumn=""38"" document=""1"" /> <entry offset=""0xb6"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""30"" document=""1"" /> <entry offset=""0xbd"" hidden=""true"" document=""1"" /> <entry offset=""0xbf"" startLine=""19"" startColumn=""32"" endLine=""19"" endColumn=""38"" document=""1"" /> <entry offset=""0xc1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc2""> <scope startOffset=""0x1b"" endOffset=""0x29""> <local name=""i"" il_index=""1"" il_start=""0x1b"" il_end=""0x29"" attributes=""0"" /> </scope> <scope startOffset=""0x4a"" endOffset=""0x57""> <local name=""i"" il_index=""2"" il_start=""0x4a"" il_end=""0x57"" attributes=""0"" /> </scope> <scope startOffset=""0x78"" endOffset=""0x85""> <local name=""i"" il_index=""3"" il_start=""0x78"" il_end=""0x85"" attributes=""0"" /> </scope> <scope startOffset=""0xa8"" endOffset=""0xb6""> <local name=""i"" il_index=""4"" il_start=""0xa8"" il_end=""0xb6"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")] public void TestSignificanceOfDynamicVersusObjectAndTupleNamesInUniquenessOfPatternMatchingTemps() { var source = @"using System; public class Generic<T,U> { } class Program { public static void Main(string[] args) { var g = new Generic<object, (int, int)>(); M2(g, true, false, false); M2(g, false, true, false); M2(g, false, false, true); } public static void M2(object o, bool b1, bool b2, bool b3) { switch (o) { case Generic<object, (int a, int b)> g when b1: Console.Write(""a""); break; case var _ when b2: Console.Write(""b""); break; case Generic<dynamic, (int x, int y)> g when b3: Console.Write(""c""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "abc"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 98 (0x62) .maxstack 2 .locals init (int V_0, Generic<object, System.ValueTuple<int, int>> V_1, //g Generic<dynamic, System.ValueTuple<int, int>> V_2, //g object V_3, object V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.s V_4 IL_0004: ldloc.s V_4 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: isinst ""Generic<object, System.ValueTuple<int, int>>"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0013 IL_0011: br.s IL_0029 IL_0013: ldarg.1 IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0025 IL_0018: ldstr ""a"" IL_001d: call ""void System.Console.Write(string)"" IL_0022: nop IL_0023: br.s IL_0061 IL_0025: ldc.i4.1 IL_0026: stloc.0 IL_0027: br.s IL_002d IL_0029: ldc.i4.3 IL_002a: stloc.0 IL_002b: br.s IL_002d IL_002d: ldarg.2 IL_002e: brtrue.s IL_0040 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: beq.s IL_003c IL_0034: br.s IL_0036 IL_0036: ldloc.0 IL_0037: ldc.i4.3 IL_0038: beq.s IL_003e IL_003a: br.s IL_0040 IL_003c: br.s IL_004d IL_003e: br.s IL_0061 IL_0040: ldstr ""b"" IL_0045: call ""void System.Console.Write(string)"" IL_004a: nop IL_004b: br.s IL_0061 IL_004d: ldloc.1 IL_004e: stloc.2 IL_004f: ldarg.3 IL_0050: brtrue.s IL_0054 IL_0052: br.s IL_0061 IL_0054: ldstr ""c"" IL_0059: call ""void System.Console.Write(string)"" IL_005e: nop IL_005f: br.s IL_0061 IL_0061: ret } " ); } [Fact] [WorkItem(39564, "https://github.com/dotnet/roslyn/issues/39564")] public void OrderOfEvaluationOfTupleAsSwitchExpressionArgument() { var source = @"using System; class Program { public static void Main(string[] args) { using var sr = new System.IO.StringReader(""fiz\nbar""); var r = (sr.ReadLine(), sr.ReadLine()) switch { (""fiz"", ""bar"") => ""Yep, all good!"", var (a, b) => $""Wait, what? I got ({a}, {b})!"", }; Console.WriteLine(r); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!"); compVerifier.VerifyIL("Program.Main", @" { // Code size 144 (0x90) .maxstack 4 .locals init (System.IO.StringReader V_0, //sr string V_1, //r string V_2, //a string V_3, //b string V_4) IL_0000: nop IL_0001: ldstr ""fiz bar"" IL_0006: newobj ""System.IO.StringReader..ctor(string)"" IL_000b: stloc.0 .try { IL_000c: ldloc.0 IL_000d: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0012: stloc.2 IL_0013: ldloc.0 IL_0014: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0019: stloc.3 IL_001a: ldc.i4.1 IL_001b: brtrue.s IL_001e IL_001d: nop IL_001e: ldloc.2 IL_001f: ldstr ""fiz"" IL_0024: call ""bool string.op_Equality(string, string)"" IL_0029: brfalse.s IL_0043 IL_002b: ldloc.3 IL_002c: ldstr ""bar"" IL_0031: call ""bool string.op_Equality(string, string)"" IL_0036: brtrue.s IL_003a IL_0038: br.s IL_0043 IL_003a: ldstr ""Yep, all good!"" IL_003f: stloc.s V_4 IL_0041: br.s IL_0074 IL_0043: br.s IL_0045 IL_0045: ldc.i4.5 IL_0046: newarr ""string"" IL_004b: dup IL_004c: ldc.i4.0 IL_004d: ldstr ""Wait, what? I got ("" IL_0052: stelem.ref IL_0053: dup IL_0054: ldc.i4.1 IL_0055: ldloc.2 IL_0056: stelem.ref IL_0057: dup IL_0058: ldc.i4.2 IL_0059: ldstr "", "" IL_005e: stelem.ref IL_005f: dup IL_0060: ldc.i4.3 IL_0061: ldloc.3 IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.4 IL_0065: ldstr "")!"" IL_006a: stelem.ref IL_006b: call ""string string.Concat(params string[])"" IL_0070: stloc.s V_4 IL_0072: br.s IL_0074 IL_0074: ldc.i4.1 IL_0075: brtrue.s IL_0078 IL_0077: nop IL_0078: ldloc.s V_4 IL_007a: stloc.1 IL_007b: ldloc.1 IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: nop IL_0082: leave.s IL_008f } finally { IL_0084: ldloc.0 IL_0085: brfalse.s IL_008e IL_0087: ldloc.0 IL_0088: callvirt ""void System.IDisposable.Dispose()"" IL_008d: nop IL_008e: endfinally } IL_008f: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe) .VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!"); compVerifier.VerifyIL("Program.Main", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.IO.StringReader V_0, //sr string V_1, //a string V_2, //b string V_3) IL_0000: ldstr ""fiz bar"" IL_0005: newobj ""System.IO.StringReader..ctor(string)"" IL_000a: stloc.0 .try { IL_000b: ldloc.0 IL_000c: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0018: stloc.2 IL_0019: ldloc.1 IL_001a: ldstr ""fiz"" IL_001f: call ""bool string.op_Equality(string, string)"" IL_0024: brfalse.s IL_003b IL_0026: ldloc.2 IL_0027: ldstr ""bar"" IL_002c: call ""bool string.op_Equality(string, string)"" IL_0031: brfalse.s IL_003b IL_0033: ldstr ""Yep, all good!"" IL_0038: stloc.3 IL_0039: br.s IL_0067 IL_003b: ldc.i4.5 IL_003c: newarr ""string"" IL_0041: dup IL_0042: ldc.i4.0 IL_0043: ldstr ""Wait, what? I got ("" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldloc.1 IL_004c: stelem.ref IL_004d: dup IL_004e: ldc.i4.2 IL_004f: ldstr "", "" IL_0054: stelem.ref IL_0055: dup IL_0056: ldc.i4.3 IL_0057: ldloc.2 IL_0058: stelem.ref IL_0059: dup IL_005a: ldc.i4.4 IL_005b: ldstr "")!"" IL_0060: stelem.ref IL_0061: call ""string string.Concat(params string[])"" IL_0066: stloc.3 IL_0067: ldloc.3 IL_0068: call ""void System.Console.WriteLine(string)"" IL_006d: leave.s IL_0079 } finally { IL_006f: ldloc.0 IL_0070: brfalse.s IL_0078 IL_0072: ldloc.0 IL_0073: callvirt ""void System.IDisposable.Dispose()"" IL_0078: endfinally } IL_0079: ret } "); } [Fact] [WorkItem(41502, "https://github.com/dotnet/roslyn/issues/41502")] public void PatternSwitchDagReduction_01() { var source = @"using System; class Program { public static void Main(string[] args) { M(1, 1, 6); // 1 M(1, 2, 6); // 2 M(1, 1, 3); // 3 M(1, 2, 3); // 3 M(1, 5, 3); // 3 M(2, 5, 3); // 3 M(1, 3, 4); // 4 M(2, 1, 4); // 5 M(2, 2, 2); // 6 } public static void M(int a, int b, int c) => Console.Write(M2(a, b, c)); public static int M2(int a, int b, int c) => (a, b, c) switch { (1, 1, 6) => 1, (1, 2, 6) => 2, (_, _, 3) => 3, (1, _, _) => 4, (_, 1, _) => 5, (_, _, _) => 6, }; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456"); compVerifier.VerifyIL("Program.M2", @" { // Code size 76 (0x4c) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.0 IL_0005: ldc.i4.1 IL_0006: bne.un.s IL_0024 IL_0008: ldarg.1 IL_0009: ldc.i4.1 IL_000a: beq.s IL_0014 IL_000c: br.s IL_000e IL_000e: ldarg.1 IL_000f: ldc.i4.2 IL_0010: beq.s IL_001a IL_0012: br.s IL_001e IL_0014: ldarg.2 IL_0015: ldc.i4.6 IL_0016: beq.s IL_002e IL_0018: br.s IL_001e IL_001a: ldarg.2 IL_001b: ldc.i4.6 IL_001c: beq.s IL_0032 IL_001e: ldarg.2 IL_001f: ldc.i4.3 IL_0020: beq.s IL_0036 IL_0022: br.s IL_003a IL_0024: ldarg.2 IL_0025: ldc.i4.3 IL_0026: beq.s IL_0036 IL_0028: ldarg.1 IL_0029: ldc.i4.1 IL_002a: beq.s IL_003e IL_002c: br.s IL_0042 IL_002e: ldc.i4.1 IL_002f: stloc.0 IL_0030: br.s IL_0046 IL_0032: ldc.i4.2 IL_0033: stloc.0 IL_0034: br.s IL_0046 IL_0036: ldc.i4.3 IL_0037: stloc.0 IL_0038: br.s IL_0046 IL_003a: ldc.i4.4 IL_003b: stloc.0 IL_003c: br.s IL_0046 IL_003e: ldc.i4.5 IL_003f: stloc.0 IL_0040: br.s IL_0046 IL_0042: ldc.i4.6 IL_0043: stloc.0 IL_0044: br.s IL_0046 IL_0046: ldc.i4.1 IL_0047: brtrue.s IL_004a IL_0049: nop IL_004a: ldloc.0 IL_004b: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456"); compVerifier.VerifyIL("Program.M2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_001e IL_0004: ldarg.1 IL_0005: ldc.i4.1 IL_0006: beq.s IL_000e IL_0008: ldarg.1 IL_0009: ldc.i4.2 IL_000a: beq.s IL_0014 IL_000c: br.s IL_0018 IL_000e: ldarg.2 IL_000f: ldc.i4.6 IL_0010: beq.s IL_0028 IL_0012: br.s IL_0018 IL_0014: ldarg.2 IL_0015: ldc.i4.6 IL_0016: beq.s IL_002c IL_0018: ldarg.2 IL_0019: ldc.i4.3 IL_001a: beq.s IL_0030 IL_001c: br.s IL_0034 IL_001e: ldarg.2 IL_001f: ldc.i4.3 IL_0020: beq.s IL_0030 IL_0022: ldarg.1 IL_0023: ldc.i4.1 IL_0024: beq.s IL_0038 IL_0026: br.s IL_003c IL_0028: ldc.i4.1 IL_0029: stloc.0 IL_002a: br.s IL_003e IL_002c: ldc.i4.2 IL_002d: stloc.0 IL_002e: br.s IL_003e IL_0030: ldc.i4.3 IL_0031: stloc.0 IL_0032: br.s IL_003e IL_0034: ldc.i4.4 IL_0035: stloc.0 IL_0036: br.s IL_003e IL_0038: ldc.i4.5 IL_0039: stloc.0 IL_003a: br.s IL_003e IL_003c: ldc.i4.6 IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: ret } "); } #endregion "regression tests" #region Code Quality tests [Fact] public void BalancedSwitchDispatch_Double() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1D)); Console.WriteLine(M(3.1D)); Console.WriteLine(M(4.1D)); Console.WriteLine(M(5.1D)); Console.WriteLine(M(6.1D)); Console.WriteLine(M(7.1D)); Console.WriteLine(M(8.1D)); Console.WriteLine(M(9.1D)); Console.WriteLine(M(10.1D)); Console.WriteLine(M(11.1D)); Console.WriteLine(M(12.1D)); Console.WriteLine(M(13.1D)); Console.WriteLine(M(14.1D)); Console.WriteLine(M(15.1D)); Console.WriteLine(M(16.1D)); Console.WriteLine(M(17.1D)); Console.WriteLine(M(18.1D)); Console.WriteLine(M(19.1D)); Console.WriteLine(M(20.1D)); Console.WriteLine(M(21.1D)); Console.WriteLine(M(22.1D)); Console.WriteLine(M(23.1D)); Console.WriteLine(M(24.1D)); Console.WriteLine(M(25.1D)); Console.WriteLine(M(26.1D)); Console.WriteLine(M(27.1D)); Console.WriteLine(M(28.1D)); Console.WriteLine(M(29.1D)); } static int M(double d) { return d switch { >= 27.1D and < 29.1D => 19, 26.1D => 18, 9.1D => 5, >= 2.1D and < 4.1D => 1, 12.1D => 8, >= 21.1D and < 23.1D => 15, 19.1D => 13, 29.1D => 20, >= 13.1D and < 15.1D => 9, 10.1D => 6, 15.1D => 10, 11.1D => 7, 4.1D => 2, >= 16.1D and < 18.1D => 11, >= 23.1D and < 25.1D => 16, 18.1D => 12, >= 7.1D and < 9.1D => 4, 25.1D => 17, 20.1D => 14, >= 5.1D and < 7.1D => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 499 (0x1f3) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.r8 13.1 IL_000a: blt.un IL_00fb IL_000f: ldarg.0 IL_0010: ldc.r8 21.1 IL_0019: blt.un.s IL_008b IL_001b: ldarg.0 IL_001c: ldc.r8 27.1 IL_0025: blt.un.s IL_004a IL_0027: ldarg.0 IL_0028: ldc.r8 29.1 IL_0031: blt IL_0193 IL_0036: ldarg.0 IL_0037: ldc.r8 29.1 IL_0040: beq IL_01b3 IL_0045: br IL_01ef IL_004a: ldarg.0 IL_004b: ldc.r8 23.1 IL_0054: blt IL_01a9 IL_0059: ldarg.0 IL_005a: ldc.r8 25.1 IL_0063: blt IL_01d3 IL_0068: ldarg.0 IL_0069: ldc.r8 25.1 IL_0072: beq IL_01e1 IL_0077: ldarg.0 IL_0078: ldc.r8 26.1 IL_0081: beq IL_0198 IL_0086: br IL_01ef IL_008b: ldarg.0 IL_008c: ldc.r8 16.1 IL_0095: blt.un.s IL_00d8 IL_0097: ldarg.0 IL_0098: ldc.r8 18.1 IL_00a1: blt IL_01ce IL_00a6: ldarg.0 IL_00a7: ldc.r8 18.1 IL_00b0: beq IL_01d8 IL_00b5: ldarg.0 IL_00b6: ldc.r8 19.1 IL_00bf: beq IL_01ae IL_00c4: ldarg.0 IL_00c5: ldc.r8 20.1 IL_00ce: beq IL_01e6 IL_00d3: br IL_01ef IL_00d8: ldarg.0 IL_00d9: ldc.r8 15.1 IL_00e2: blt IL_01b8 IL_00e7: ldarg.0 IL_00e8: ldc.r8 15.1 IL_00f1: beq IL_01c1 IL_00f6: br IL_01ef IL_00fb: ldarg.0 IL_00fc: ldc.r8 7.1 IL_0105: blt.un.s IL_015f IL_0107: ldarg.0 IL_0108: ldc.r8 9.1 IL_0111: blt IL_01dd IL_0116: ldarg.0 IL_0117: ldc.r8 10.1 IL_0120: bgt.un.s IL_0142 IL_0122: ldarg.0 IL_0123: ldc.r8 9.1 IL_012c: beq.s IL_019d IL_012e: ldarg.0 IL_012f: ldc.r8 10.1 IL_0138: beq IL_01bd IL_013d: br IL_01ef IL_0142: ldarg.0 IL_0143: ldc.r8 11.1 IL_014c: beq.s IL_01c6 IL_014e: ldarg.0 IL_014f: ldc.r8 12.1 IL_0158: beq.s IL_01a5 IL_015a: br IL_01ef IL_015f: ldarg.0 IL_0160: ldc.r8 4.1 IL_0169: bge.un.s IL_0179 IL_016b: ldarg.0 IL_016c: ldc.r8 2.1 IL_0175: bge.s IL_01a1 IL_0177: br.s IL_01ef IL_0179: ldarg.0 IL_017a: ldc.r8 5.1 IL_0183: bge.s IL_01eb IL_0185: ldarg.0 IL_0186: ldc.r8 4.1 IL_018f: beq.s IL_01ca IL_0191: br.s IL_01ef IL_0193: ldc.i4.s 19 IL_0195: stloc.0 IL_0196: br.s IL_01f1 IL_0198: ldc.i4.s 18 IL_019a: stloc.0 IL_019b: br.s IL_01f1 IL_019d: ldc.i4.5 IL_019e: stloc.0 IL_019f: br.s IL_01f1 IL_01a1: ldc.i4.1 IL_01a2: stloc.0 IL_01a3: br.s IL_01f1 IL_01a5: ldc.i4.8 IL_01a6: stloc.0 IL_01a7: br.s IL_01f1 IL_01a9: ldc.i4.s 15 IL_01ab: stloc.0 IL_01ac: br.s IL_01f1 IL_01ae: ldc.i4.s 13 IL_01b0: stloc.0 IL_01b1: br.s IL_01f1 IL_01b3: ldc.i4.s 20 IL_01b5: stloc.0 IL_01b6: br.s IL_01f1 IL_01b8: ldc.i4.s 9 IL_01ba: stloc.0 IL_01bb: br.s IL_01f1 IL_01bd: ldc.i4.6 IL_01be: stloc.0 IL_01bf: br.s IL_01f1 IL_01c1: ldc.i4.s 10 IL_01c3: stloc.0 IL_01c4: br.s IL_01f1 IL_01c6: ldc.i4.7 IL_01c7: stloc.0 IL_01c8: br.s IL_01f1 IL_01ca: ldc.i4.2 IL_01cb: stloc.0 IL_01cc: br.s IL_01f1 IL_01ce: ldc.i4.s 11 IL_01d0: stloc.0 IL_01d1: br.s IL_01f1 IL_01d3: ldc.i4.s 16 IL_01d5: stloc.0 IL_01d6: br.s IL_01f1 IL_01d8: ldc.i4.s 12 IL_01da: stloc.0 IL_01db: br.s IL_01f1 IL_01dd: ldc.i4.4 IL_01de: stloc.0 IL_01df: br.s IL_01f1 IL_01e1: ldc.i4.s 17 IL_01e3: stloc.0 IL_01e4: br.s IL_01f1 IL_01e6: ldc.i4.s 14 IL_01e8: stloc.0 IL_01e9: br.s IL_01f1 IL_01eb: ldc.i4.3 IL_01ec: stloc.0 IL_01ed: br.s IL_01f1 IL_01ef: ldc.i4.0 IL_01f0: stloc.0 IL_01f1: ldloc.0 IL_01f2: ret } " ); } [Fact] public void BalancedSwitchDispatch_Float() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1F)); Console.WriteLine(M(3.1F)); Console.WriteLine(M(4.1F)); Console.WriteLine(M(5.1F)); Console.WriteLine(M(6.1F)); Console.WriteLine(M(7.1F)); Console.WriteLine(M(8.1F)); Console.WriteLine(M(9.1F)); Console.WriteLine(M(10.1F)); Console.WriteLine(M(11.1F)); Console.WriteLine(M(12.1F)); Console.WriteLine(M(13.1F)); Console.WriteLine(M(14.1F)); Console.WriteLine(M(15.1F)); Console.WriteLine(M(16.1F)); Console.WriteLine(M(17.1F)); Console.WriteLine(M(18.1F)); Console.WriteLine(M(19.1F)); Console.WriteLine(M(20.1F)); Console.WriteLine(M(21.1F)); Console.WriteLine(M(22.1F)); Console.WriteLine(M(23.1F)); Console.WriteLine(M(24.1F)); Console.WriteLine(M(25.1F)); Console.WriteLine(M(26.1F)); Console.WriteLine(M(27.1F)); Console.WriteLine(M(28.1F)); Console.WriteLine(M(29.1F)); } static int M(float d) { return d switch { >= 27.1F and < 29.1F => 19, 26.1F => 18, 9.1F => 5, >= 2.1F and < 4.1F => 1, 12.1F => 8, >= 21.1F and < 23.1F => 15, 19.1F => 13, 29.1F => 20, >= 13.1F and < 15.1F => 9, 10.1F => 6, 15.1F => 10, 11.1F => 7, 4.1F => 2, >= 16.1F and < 18.1F => 11, >= 23.1F and < 25.1F => 16, 18.1F => 12, >= 7.1F and < 9.1F => 4, 25.1F => 17, 20.1F => 14, >= 5.1F and < 7.1F => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 388 (0x184) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.r4 13.1 IL_0006: blt.un IL_00bb IL_000b: ldarg.0 IL_000c: ldc.r4 21.1 IL_0011: blt.un.s IL_0067 IL_0013: ldarg.0 IL_0014: ldc.r4 27.1 IL_0019: blt.un.s IL_0036 IL_001b: ldarg.0 IL_001c: ldc.r4 29.1 IL_0021: blt IL_0124 IL_0026: ldarg.0 IL_0027: ldc.r4 29.1 IL_002c: beq IL_0144 IL_0031: br IL_0180 IL_0036: ldarg.0 IL_0037: ldc.r4 23.1 IL_003c: blt IL_013a IL_0041: ldarg.0 IL_0042: ldc.r4 25.1 IL_0047: blt IL_0164 IL_004c: ldarg.0 IL_004d: ldc.r4 25.1 IL_0052: beq IL_0172 IL_0057: ldarg.0 IL_0058: ldc.r4 26.1 IL_005d: beq IL_0129 IL_0062: br IL_0180 IL_0067: ldarg.0 IL_0068: ldc.r4 16.1 IL_006d: blt.un.s IL_00a0 IL_006f: ldarg.0 IL_0070: ldc.r4 18.1 IL_0075: blt IL_015f IL_007a: ldarg.0 IL_007b: ldc.r4 18.1 IL_0080: beq IL_0169 IL_0085: ldarg.0 IL_0086: ldc.r4 19.1 IL_008b: beq IL_013f IL_0090: ldarg.0 IL_0091: ldc.r4 20.1 IL_0096: beq IL_0177 IL_009b: br IL_0180 IL_00a0: ldarg.0 IL_00a1: ldc.r4 15.1 IL_00a6: blt IL_0149 IL_00ab: ldarg.0 IL_00ac: ldc.r4 15.1 IL_00b1: beq IL_0152 IL_00b6: br IL_0180 IL_00bb: ldarg.0 IL_00bc: ldc.r4 7.1 IL_00c1: blt.un.s IL_0100 IL_00c3: ldarg.0 IL_00c4: ldc.r4 9.1 IL_00c9: blt IL_016e IL_00ce: ldarg.0 IL_00cf: ldc.r4 10.1 IL_00d4: bgt.un.s IL_00eb IL_00d6: ldarg.0 IL_00d7: ldc.r4 9.1 IL_00dc: beq.s IL_012e IL_00de: ldarg.0 IL_00df: ldc.r4 10.1 IL_00e4: beq.s IL_014e IL_00e6: br IL_0180 IL_00eb: ldarg.0 IL_00ec: ldc.r4 11.1 IL_00f1: beq.s IL_0157 IL_00f3: ldarg.0 IL_00f4: ldc.r4 12.1 IL_00f9: beq.s IL_0136 IL_00fb: br IL_0180 IL_0100: ldarg.0 IL_0101: ldc.r4 4.1 IL_0106: bge.un.s IL_0112 IL_0108: ldarg.0 IL_0109: ldc.r4 2.1 IL_010e: bge.s IL_0132 IL_0110: br.s IL_0180 IL_0112: ldarg.0 IL_0113: ldc.r4 5.1 IL_0118: bge.s IL_017c IL_011a: ldarg.0 IL_011b: ldc.r4 4.1 IL_0120: beq.s IL_015b IL_0122: br.s IL_0180 IL_0124: ldc.i4.s 19 IL_0126: stloc.0 IL_0127: br.s IL_0182 IL_0129: ldc.i4.s 18 IL_012b: stloc.0 IL_012c: br.s IL_0182 IL_012e: ldc.i4.5 IL_012f: stloc.0 IL_0130: br.s IL_0182 IL_0132: ldc.i4.1 IL_0133: stloc.0 IL_0134: br.s IL_0182 IL_0136: ldc.i4.8 IL_0137: stloc.0 IL_0138: br.s IL_0182 IL_013a: ldc.i4.s 15 IL_013c: stloc.0 IL_013d: br.s IL_0182 IL_013f: ldc.i4.s 13 IL_0141: stloc.0 IL_0142: br.s IL_0182 IL_0144: ldc.i4.s 20 IL_0146: stloc.0 IL_0147: br.s IL_0182 IL_0149: ldc.i4.s 9 IL_014b: stloc.0 IL_014c: br.s IL_0182 IL_014e: ldc.i4.6 IL_014f: stloc.0 IL_0150: br.s IL_0182 IL_0152: ldc.i4.s 10 IL_0154: stloc.0 IL_0155: br.s IL_0182 IL_0157: ldc.i4.7 IL_0158: stloc.0 IL_0159: br.s IL_0182 IL_015b: ldc.i4.2 IL_015c: stloc.0 IL_015d: br.s IL_0182 IL_015f: ldc.i4.s 11 IL_0161: stloc.0 IL_0162: br.s IL_0182 IL_0164: ldc.i4.s 16 IL_0166: stloc.0 IL_0167: br.s IL_0182 IL_0169: ldc.i4.s 12 IL_016b: stloc.0 IL_016c: br.s IL_0182 IL_016e: ldc.i4.4 IL_016f: stloc.0 IL_0170: br.s IL_0182 IL_0172: ldc.i4.s 17 IL_0174: stloc.0 IL_0175: br.s IL_0182 IL_0177: ldc.i4.s 14 IL_0179: stloc.0 IL_017a: br.s IL_0182 IL_017c: ldc.i4.3 IL_017d: stloc.0 IL_017e: br.s IL_0182 IL_0180: ldc.i4.0 IL_0181: stloc.0 IL_0182: ldloc.0 IL_0183: ret } " ); } [Fact] public void BalancedSwitchDispatch_Decimal() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1M)); Console.WriteLine(M(3.1M)); Console.WriteLine(M(4.1M)); Console.WriteLine(M(5.1M)); Console.WriteLine(M(6.1M)); Console.WriteLine(M(7.1M)); Console.WriteLine(M(8.1M)); Console.WriteLine(M(9.1M)); Console.WriteLine(M(10.1M)); Console.WriteLine(M(11.1M)); Console.WriteLine(M(12.1M)); Console.WriteLine(M(13.1M)); Console.WriteLine(M(14.1M)); Console.WriteLine(M(15.1M)); Console.WriteLine(M(16.1M)); Console.WriteLine(M(17.1M)); Console.WriteLine(M(18.1M)); Console.WriteLine(M(19.1M)); Console.WriteLine(M(20.1M)); Console.WriteLine(M(21.1M)); Console.WriteLine(M(22.1M)); Console.WriteLine(M(23.1M)); Console.WriteLine(M(24.1M)); Console.WriteLine(M(25.1M)); Console.WriteLine(M(26.1M)); Console.WriteLine(M(27.1M)); Console.WriteLine(M(28.1M)); Console.WriteLine(M(29.1M)); } static int M(decimal d) { return d switch { >= 27.1M and < 29.1M => 19, 26.1M => 18, 9.1M => 5, >= 2.1M and < 4.1M => 1, 12.1M => 8, >= 21.1M and < 23.1M => 15, 19.1M => 13, 29.1M => 20, >= 13.1M and < 15.1M => 9, 10.1M => 6, 15.1M => 10, 11.1M => 7, 4.1M => 2, >= 16.1M and < 18.1M => 11, >= 23.1M and < 25.1M => 16, 18.1M => 12, >= 7.1M and < 9.1M => 4, 25.1M => 17, 20.1M => 14, >= 5.1M and < 7.1M => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 751 (0x2ef) .maxstack 6 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4 0x83 IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000f: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0014: brfalse IL_019e IL_0019: ldarg.0 IL_001a: ldc.i4 0xd3 IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: ldc.i4.1 IL_0023: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0028: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_002d: brfalse IL_00e8 IL_0032: ldarg.0 IL_0033: ldc.i4 0x10f IL_0038: ldc.i4.0 IL_0039: ldc.i4.0 IL_003a: ldc.i4.0 IL_003b: ldc.i4.1 IL_003c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0041: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0046: brfalse.s IL_007f IL_0048: ldarg.0 IL_0049: ldc.i4 0x123 IL_004e: ldc.i4.0 IL_004f: ldc.i4.0 IL_0050: ldc.i4.0 IL_0051: ldc.i4.1 IL_0052: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0057: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_005c: brtrue IL_028f IL_0061: ldarg.0 IL_0062: ldc.i4 0x123 IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldc.i4.0 IL_006a: ldc.i4.1 IL_006b: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0070: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0075: brtrue IL_02af IL_007a: br IL_02eb IL_007f: ldarg.0 IL_0080: ldc.i4 0xe7 IL_0085: ldc.i4.0 IL_0086: ldc.i4.0 IL_0087: ldc.i4.0 IL_0088: ldc.i4.1 IL_0089: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_008e: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_0093: brtrue IL_02a5 IL_0098: ldarg.0 IL_0099: ldc.i4 0xfb IL_009e: ldc.i4.0 IL_009f: ldc.i4.0 IL_00a0: ldc.i4.0 IL_00a1: ldc.i4.1 IL_00a2: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00a7: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_00ac: brtrue IL_02cf IL_00b1: ldarg.0 IL_00b2: ldc.i4 0xfb IL_00b7: ldc.i4.0 IL_00b8: ldc.i4.0 IL_00b9: ldc.i4.0 IL_00ba: ldc.i4.1 IL_00bb: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00c0: call ""bool decimal.op_Equality(decimal, decimal)"" IL_00c5: brtrue IL_02dd IL_00ca: ldarg.0 IL_00cb: ldc.i4 0x105 IL_00d0: ldc.i4.0 IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldc.i4.1 IL_00d4: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00d9: call ""bool decimal.op_Equality(decimal, decimal)"" IL_00de: brtrue IL_0294 IL_00e3: br IL_02eb IL_00e8: ldarg.0 IL_00e9: ldc.i4 0xa1 IL_00ee: ldc.i4.0 IL_00ef: ldc.i4.0 IL_00f0: ldc.i4.0 IL_00f1: ldc.i4.1 IL_00f2: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00f7: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_00fc: brfalse.s IL_0167 IL_00fe: ldarg.0 IL_00ff: ldc.i4 0xb5 IL_0104: ldc.i4.0 IL_0105: ldc.i4.0 IL_0106: ldc.i4.0 IL_0107: ldc.i4.1 IL_0108: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_010d: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_0112: brtrue IL_02ca IL_0117: ldarg.0 IL_0118: ldc.i4 0xb5 IL_011d: ldc.i4.0 IL_011e: ldc.i4.0 IL_011f: ldc.i4.0 IL_0120: ldc.i4.1 IL_0121: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0126: call ""bool decimal.op_Equality(decimal, decimal)"" IL_012b: brtrue IL_02d4 IL_0130: ldarg.0 IL_0131: ldc.i4 0xbf IL_0136: ldc.i4.0 IL_0137: ldc.i4.0 IL_0138: ldc.i4.0 IL_0139: ldc.i4.1 IL_013a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_013f: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0144: brtrue IL_02aa IL_0149: ldarg.0 IL_014a: ldc.i4 0xc9 IL_014f: ldc.i4.0 IL_0150: ldc.i4.0 IL_0151: ldc.i4.0 IL_0152: ldc.i4.1 IL_0153: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0158: call ""bool decimal.op_Equality(decimal, decimal)"" IL_015d: brtrue IL_02e2 IL_0162: br IL_02eb IL_0167: ldarg.0 IL_0168: ldc.i4 0x97 IL_016d: ldc.i4.0 IL_016e: ldc.i4.0 IL_016f: ldc.i4.0 IL_0170: ldc.i4.1 IL_0171: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0176: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_017b: brtrue IL_02b4 IL_0180: ldarg.0 IL_0181: ldc.i4 0x97 IL_0186: ldc.i4.0 IL_0187: ldc.i4.0 IL_0188: ldc.i4.0 IL_0189: ldc.i4.1 IL_018a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_018f: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0194: brtrue IL_02bd IL_0199: br IL_02eb IL_019e: ldarg.0 IL_019f: ldc.i4.s 71 IL_01a1: ldc.i4.0 IL_01a2: ldc.i4.0 IL_01a3: ldc.i4.0 IL_01a4: ldc.i4.1 IL_01a5: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01aa: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_01af: brfalse IL_023c IL_01b4: ldarg.0 IL_01b5: ldc.i4.s 91 IL_01b7: ldc.i4.0 IL_01b8: ldc.i4.0 IL_01b9: ldc.i4.0 IL_01ba: ldc.i4.1 IL_01bb: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01c0: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_01c5: brtrue IL_02d9 IL_01ca: ldarg.0 IL_01cb: ldc.i4.s 101 IL_01cd: ldc.i4.0 IL_01ce: ldc.i4.0 IL_01cf: ldc.i4.0 IL_01d0: ldc.i4.1 IL_01d1: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01d6: call ""bool decimal.op_LessThanOrEqual(decimal, decimal)"" IL_01db: brfalse.s IL_020e IL_01dd: ldarg.0 IL_01de: ldc.i4.s 91 IL_01e0: ldc.i4.0 IL_01e1: ldc.i4.0 IL_01e2: ldc.i4.0 IL_01e3: ldc.i4.1 IL_01e4: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01e9: call ""bool decimal.op_Equality(decimal, decimal)"" IL_01ee: brtrue IL_0299 IL_01f3: ldarg.0 IL_01f4: ldc.i4.s 101 IL_01f6: ldc.i4.0 IL_01f7: ldc.i4.0 IL_01f8: ldc.i4.0 IL_01f9: ldc.i4.1 IL_01fa: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01ff: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0204: brtrue IL_02b9 IL_0209: br IL_02eb IL_020e: ldarg.0 IL_020f: ldc.i4.s 111 IL_0211: ldc.i4.0 IL_0212: ldc.i4.0 IL_0213: ldc.i4.0 IL_0214: ldc.i4.1 IL_0215: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_021a: call ""bool decimal.op_Equality(decimal, decimal)"" IL_021f: brtrue IL_02c2 IL_0224: ldarg.0 IL_0225: ldc.i4.s 121 IL_0227: ldc.i4.0 IL_0228: ldc.i4.0 IL_0229: ldc.i4.0 IL_022a: ldc.i4.1 IL_022b: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0230: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0235: brtrue.s IL_02a1 IL_0237: br IL_02eb IL_023c: ldarg.0 IL_023d: ldc.i4.s 41 IL_023f: ldc.i4.0 IL_0240: ldc.i4.0 IL_0241: ldc.i4.0 IL_0242: ldc.i4.1 IL_0243: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0248: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_024d: brfalse.s IL_0267 IL_024f: ldarg.0 IL_0250: ldc.i4.s 21 IL_0252: ldc.i4.0 IL_0253: ldc.i4.0 IL_0254: ldc.i4.0 IL_0255: ldc.i4.1 IL_0256: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_025b: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0260: brtrue.s IL_029d IL_0262: br IL_02eb IL_0267: ldarg.0 IL_0268: ldc.i4.s 51 IL_026a: ldc.i4.0 IL_026b: ldc.i4.0 IL_026c: ldc.i4.0 IL_026d: ldc.i4.1 IL_026e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0273: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0278: brtrue.s IL_02e7 IL_027a: ldarg.0 IL_027b: ldc.i4.s 41 IL_027d: ldc.i4.0 IL_027e: ldc.i4.0 IL_027f: ldc.i4.0 IL_0280: ldc.i4.1 IL_0281: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0286: call ""bool decimal.op_Equality(decimal, decimal)"" IL_028b: brtrue.s IL_02c6 IL_028d: br.s IL_02eb IL_028f: ldc.i4.s 19 IL_0291: stloc.0 IL_0292: br.s IL_02ed IL_0294: ldc.i4.s 18 IL_0296: stloc.0 IL_0297: br.s IL_02ed IL_0299: ldc.i4.5 IL_029a: stloc.0 IL_029b: br.s IL_02ed IL_029d: ldc.i4.1 IL_029e: stloc.0 IL_029f: br.s IL_02ed IL_02a1: ldc.i4.8 IL_02a2: stloc.0 IL_02a3: br.s IL_02ed IL_02a5: ldc.i4.s 15 IL_02a7: stloc.0 IL_02a8: br.s IL_02ed IL_02aa: ldc.i4.s 13 IL_02ac: stloc.0 IL_02ad: br.s IL_02ed IL_02af: ldc.i4.s 20 IL_02b1: stloc.0 IL_02b2: br.s IL_02ed IL_02b4: ldc.i4.s 9 IL_02b6: stloc.0 IL_02b7: br.s IL_02ed IL_02b9: ldc.i4.6 IL_02ba: stloc.0 IL_02bb: br.s IL_02ed IL_02bd: ldc.i4.s 10 IL_02bf: stloc.0 IL_02c0: br.s IL_02ed IL_02c2: ldc.i4.7 IL_02c3: stloc.0 IL_02c4: br.s IL_02ed IL_02c6: ldc.i4.2 IL_02c7: stloc.0 IL_02c8: br.s IL_02ed IL_02ca: ldc.i4.s 11 IL_02cc: stloc.0 IL_02cd: br.s IL_02ed IL_02cf: ldc.i4.s 16 IL_02d1: stloc.0 IL_02d2: br.s IL_02ed IL_02d4: ldc.i4.s 12 IL_02d6: stloc.0 IL_02d7: br.s IL_02ed IL_02d9: ldc.i4.4 IL_02da: stloc.0 IL_02db: br.s IL_02ed IL_02dd: ldc.i4.s 17 IL_02df: stloc.0 IL_02e0: br.s IL_02ed IL_02e2: ldc.i4.s 14 IL_02e4: stloc.0 IL_02e5: br.s IL_02ed IL_02e7: ldc.i4.3 IL_02e8: stloc.0 IL_02e9: br.s IL_02ed IL_02eb: ldc.i4.0 IL_02ec: stloc.0 IL_02ed: ldloc.0 IL_02ee: ret } " ); } [Fact] public void BalancedSwitchDispatch_Uint32() { // We do not currently detect that the set of values that we are dispatching on is a compact set, // which would enable us to use the IL switch instruction even though the input was expressed using // a set of relational comparisons. var source = @"using System; class C { static void Main() { Console.WriteLine(M(2U)); Console.WriteLine(M(3U)); Console.WriteLine(M(4U)); Console.WriteLine(M(5U)); Console.WriteLine(M(6U)); Console.WriteLine(M(7U)); Console.WriteLine(M(8U)); Console.WriteLine(M(9U)); Console.WriteLine(M(10U)); Console.WriteLine(M(11U)); Console.WriteLine(M(12U)); Console.WriteLine(M(13U)); Console.WriteLine(M(14U)); Console.WriteLine(M(15U)); Console.WriteLine(M(16U)); Console.WriteLine(M(17U)); Console.WriteLine(M(18U)); Console.WriteLine(M(19U)); Console.WriteLine(M(20U)); Console.WriteLine(M(21U)); Console.WriteLine(M(22U)); Console.WriteLine(M(23U)); Console.WriteLine(M(24U)); Console.WriteLine(M(25U)); Console.WriteLine(M(26U)); Console.WriteLine(M(27U)); Console.WriteLine(M(28U)); Console.WriteLine(M(29U)); } static int M(uint d) { return d switch { >= 27U and < 29U => 19, 26U => 18, 9U => 5, >= 2U and < 4U => 1, 12U => 8, >= 21U and < 23U => 15, 19U => 13, 29U => 20, >= 13U and < 15U => 9, 10U => 6, 15U => 10, 11U => 7, 4U => 2, >= 16U and < 18U => 11, >= 23U and < 25U => 16, 18U => 12, >= 7U and < 9U => 4, 25U => 17, 20U => 14, >= 5U and < 7U => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 243 (0xf3) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 21 IL_0003: blt.un.s IL_0039 IL_0005: ldarg.0 IL_0006: ldc.i4.s 27 IL_0008: blt.un.s IL_001f IL_000a: ldarg.0 IL_000b: ldc.i4.s 29 IL_000d: blt.un IL_0093 IL_0012: ldarg.0 IL_0013: ldc.i4.s 29 IL_0015: beq IL_00b3 IL_001a: br IL_00ef IL_001f: ldarg.0 IL_0020: ldc.i4.s 23 IL_0022: blt.un IL_00a9 IL_0027: ldarg.0 IL_0028: ldc.i4.s 25 IL_002a: blt.un IL_00d3 IL_002f: ldarg.0 IL_0030: ldc.i4.s 26 IL_0032: beq.s IL_0098 IL_0034: br IL_00e1 IL_0039: ldarg.0 IL_003a: ldc.i4.s 13 IL_003c: blt.un.s IL_0061 IL_003e: ldarg.0 IL_003f: ldc.i4.s 15 IL_0041: blt.un.s IL_00b8 IL_0043: ldarg.0 IL_0044: ldc.i4.s 18 IL_0046: bge.un.s IL_004f IL_0048: ldarg.0 IL_0049: ldc.i4.s 15 IL_004b: beq.s IL_00c1 IL_004d: br.s IL_00ce IL_004f: ldarg.0 IL_0050: ldc.i4.s 18 IL_0052: beq IL_00d8 IL_0057: ldarg.0 IL_0058: ldc.i4.s 19 IL_005a: beq.s IL_00ae IL_005c: br IL_00e6 IL_0061: ldarg.0 IL_0062: ldc.i4.4 IL_0063: bge.un.s IL_006e IL_0065: ldarg.0 IL_0066: ldc.i4.2 IL_0067: bge.un.s IL_00a1 IL_0069: br IL_00ef IL_006e: ldarg.0 IL_006f: ldc.i4.7 IL_0070: blt.un.s IL_008d IL_0072: ldarg.0 IL_0073: ldc.i4.s 9 IL_0075: sub IL_0076: switch ( IL_009d, IL_00bd, IL_00c6, IL_00a5) IL_008b: br.s IL_00dd IL_008d: ldarg.0 IL_008e: ldc.i4.4 IL_008f: beq.s IL_00ca IL_0091: br.s IL_00eb IL_0093: ldc.i4.s 19 IL_0095: stloc.0 IL_0096: br.s IL_00f1 IL_0098: ldc.i4.s 18 IL_009a: stloc.0 IL_009b: br.s IL_00f1 IL_009d: ldc.i4.5 IL_009e: stloc.0 IL_009f: br.s IL_00f1 IL_00a1: ldc.i4.1 IL_00a2: stloc.0 IL_00a3: br.s IL_00f1 IL_00a5: ldc.i4.8 IL_00a6: stloc.0 IL_00a7: br.s IL_00f1 IL_00a9: ldc.i4.s 15 IL_00ab: stloc.0 IL_00ac: br.s IL_00f1 IL_00ae: ldc.i4.s 13 IL_00b0: stloc.0 IL_00b1: br.s IL_00f1 IL_00b3: ldc.i4.s 20 IL_00b5: stloc.0 IL_00b6: br.s IL_00f1 IL_00b8: ldc.i4.s 9 IL_00ba: stloc.0 IL_00bb: br.s IL_00f1 IL_00bd: ldc.i4.6 IL_00be: stloc.0 IL_00bf: br.s IL_00f1 IL_00c1: ldc.i4.s 10 IL_00c3: stloc.0 IL_00c4: br.s IL_00f1 IL_00c6: ldc.i4.7 IL_00c7: stloc.0 IL_00c8: br.s IL_00f1 IL_00ca: ldc.i4.2 IL_00cb: stloc.0 IL_00cc: br.s IL_00f1 IL_00ce: ldc.i4.s 11 IL_00d0: stloc.0 IL_00d1: br.s IL_00f1 IL_00d3: ldc.i4.s 16 IL_00d5: stloc.0 IL_00d6: br.s IL_00f1 IL_00d8: ldc.i4.s 12 IL_00da: stloc.0 IL_00db: br.s IL_00f1 IL_00dd: ldc.i4.4 IL_00de: stloc.0 IL_00df: br.s IL_00f1 IL_00e1: ldc.i4.s 17 IL_00e3: stloc.0 IL_00e4: br.s IL_00f1 IL_00e6: ldc.i4.s 14 IL_00e8: stloc.0 IL_00e9: br.s IL_00f1 IL_00eb: ldc.i4.3 IL_00ec: stloc.0 IL_00ed: br.s IL_00f1 IL_00ef: ldc.i4.0 IL_00f0: stloc.0 IL_00f1: ldloc.0 IL_00f2: ret } " ); } #endregion Code Quality tests } }
// Licensed to the .NET Foundation under one or more 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class SwitchTests : EmitMetadataTestBase { #region Functionality tests [Fact] public void DefaultOnlySwitch() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { default: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }"); } [WorkItem(542298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542298")] [Fact] public void DefaultOnlySwitch_02() { string text = @"using System; public class Test { public static void Main() { int status = 2; switch (status) { default: status--; break; } string str = ""string""; switch (str) { default: status--; break; } Console.WriteLine(status); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.1 IL_0004: sub IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }" ); } [Fact] public void ConstantIntegerSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { case true: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }" ); } [Fact] public void ConstantNullSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; const string s = null; switch (s) { case null: ret = 0; break; } Console.Write(ret); return(ret); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: dup IL_0002: call ""void System.Console.Write(int)"" IL_0007: ret }" ); } [Fact] public void NonConstantSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; int value = 1; switch (value) { case 2: ret = 1; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: bne.un.s IL_0008 IL_0006: ldc.i4.1 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""void System.Console.Write(int)"" IL_000e: ldloc.0 IL_000f: ret }" ); } [Fact] public void ConstantVariableInCaseLabel() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; int value = 23; switch (value) { case kValue: ret = 0; break; default: ret = 1; break; } Console.Write(ret); return(ret); } const int kValue = 23; }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.s 23 IL_0004: ldc.i4.s 23 IL_0006: bne.un.s IL_000c IL_0008: ldc.i4.0 IL_0009: stloc.0 IL_000a: br.s IL_000e IL_000c: ldc.i4.1 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void System.Console.Write(int)"" IL_0014: ldloc.0 IL_0015: ret }" ); } [Fact] public void DefaultExpressionInLabel() { var source = @" class C { static void Main() { switch (0) { case default(int): return; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void SwitchWith_NoMatchingCaseLabel_And_NoDefaultLabel() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case 1: case 2: case 3: return 1; case 1001: case 1002: case 1003: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: ldc.i4.2 IL_0006: ble.un.s IL_0014 IL_0008: ldloc.0 IL_0009: ldc.i4 0x3e9 IL_000e: sub IL_000f: ldc.i4.2 IL_0010: ble.un.s IL_0016 IL_0012: br.s IL_0018 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.2 IL_0017: ret IL_0018: ldc.i4.0 IL_0019: ret }" ); } [Fact] public void DegenerateSwitch001() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(100); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; case 100: goto case 3; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.6 IL_0002: ble.un.s IL_0009 IL_0004: ldarg.0 IL_0005: ldc.i4.s 100 IL_0007: bne.un.s IL_000b IL_0009: ldc.i4.1 IL_000a: ret IL_000b: ldc.i4.0 IL_000c: ret }" ); } [Fact] public void DegenerateSwitch001_Debug() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(100); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; case 100: goto case 3; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1", options: TestOptions.DebugExe); compVerifier.VerifyIL("Test.M", @" { // Code size 30 (0x1e) .maxstack 2 .locals init (int V_0, int V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: stloc.0 IL_0005: ldloc.0 IL_0006: ldc.i4.6 IL_0007: ble.un.s IL_0012 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ldc.i4.s 100 IL_000e: beq.s IL_0016 IL_0010: br.s IL_0018 IL_0012: ldc.i4.1 IL_0013: stloc.2 IL_0014: br.s IL_001c IL_0016: br.s IL_0012 IL_0018: ldc.i4.0 IL_0019: stloc.2 IL_001a: br.s IL_001c IL_001c: ldloc.2 IL_001d: ret }" ); } [Fact] public void DegenerateSwitch002() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(5); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.5 IL_0004: bgt.un.s IL_0008 IL_0006: ldc.i4.1 IL_0007: ret IL_0008: ldc.i4.0 IL_0009: ret } " ); } [Fact] public void DegenerateSwitch003() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(4); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case -2: case -1: case 0: case 2: case 1: case 4: case 3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s -2 IL_0003: sub IL_0004: ldc.i4.6 IL_0005: bgt.un.s IL_0009 IL_0007: ldc.i4.1 IL_0008: ret IL_0009: ldc.i4.0 IL_000a: ret }" ); } [Fact] public void DegenerateSwitch004() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(int.MaxValue - 1); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case int.MinValue + 1: case int.MinValue: case int.MaxValue: case int.MaxValue - 1: case int.MaxValue - 2: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x80000000 IL_0006: sub IL_0007: ldc.i4.1 IL_0008: ble.un.s IL_0014 IL_000a: ldarg.0 IL_000b: ldc.i4 0x7ffffffd IL_0010: sub IL_0011: ldc.i4.2 IL_0012: bgt.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } [Fact] public void DegenerateSwitch005() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(int.MaxValue + 1L); Console.Write(ret); return(ret); } public static int M(long i) { switch (i) { case int.MaxValue: case int.MaxValue + 1L: case int.MaxValue + 2L: case int.MaxValue + 3L: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x7fffffff IL_0006: conv.i8 IL_0007: sub IL_0008: ldc.i4.3 IL_0009: conv.i8 IL_000a: bgt.un.s IL_000e IL_000c: ldc.i4.1 IL_000d: ret IL_000e: ldc.i4.0 IL_000f: ret }" ); } [Fact] public void DegenerateSwitch006() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(35); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; case 31: case 35: case 36: case 33: case 34: case 32: return 4; case 41: case 45: case 46: case 43: case 44: case 42: return 5; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "4"); compVerifier.VerifyIL("Test.M", @" { // Code size 30 (0x1e) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: ldc.i4.5 IL_0004: ble.un.s IL_0016 IL_0006: ldarg.0 IL_0007: ldc.i4.s 31 IL_0009: sub IL_000a: ldc.i4.5 IL_000b: ble.un.s IL_0018 IL_000d: ldarg.0 IL_000e: ldc.i4.s 41 IL_0010: sub IL_0011: ldc.i4.5 IL_0012: ble.un.s IL_001a IL_0014: br.s IL_001c IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldc.i4.4 IL_0019: ret IL_001a: ldc.i4.5 IL_001b: ret IL_001c: ldc.i4.0 IL_001d: ret }" ); } [Fact] public void NotDegenerateSwitch006() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(35); Console.Write(ret); return(ret); } public static int M(int i) { switch (i) { case 1: case 5: case 6: case 3: case 4: case 2: return 1; case 11: case 15: case 16: case 13: case 14: case 12: return 2; case 21: case 25: case 26: case 23: case 24: case 22: return 3; case 31: case 35: case 36: case 33: case 34: case 32: return 4; case 41: case 45: case 46: case 43: case 44: case 42: return 5; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "4"); compVerifier.VerifyIL("Test.M", @" { // Code size 206 (0xce) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: sub IL_0003: switch ( IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00c2, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00c4, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00c6, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00c8, IL_00cc, IL_00cc, IL_00cc, IL_00cc, IL_00ca, IL_00ca, IL_00ca, IL_00ca, IL_00ca, IL_00ca) IL_00c0: br.s IL_00cc IL_00c2: ldc.i4.1 IL_00c3: ret IL_00c4: ldc.i4.2 IL_00c5: ret IL_00c6: ldc.i4.3 IL_00c7: ret IL_00c8: ldc.i4.4 IL_00c9: ret IL_00ca: ldc.i4.5 IL_00cb: ret IL_00cc: ldc.i4.0 IL_00cd: ret }"); } [Fact] public void DegenerateSwitch007() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(5); Console.Write(ret); return(ret); } public static int M(int? i) { switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: return 1; default: return 0; case null: return 2; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (int V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0019 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldc.i4.6 IL_0013: bgt.un.s IL_0017 IL_0015: ldc.i4.1 IL_0016: ret IL_0017: ldc.i4.0 IL_0018: ret IL_0019: ldc.i4.2 IL_001a: ret }" ); } [Fact] public void DegenerateSwitch008() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M((uint)int.MaxValue + (uint)1); Console.Write(ret); return(ret); } public static int M(uint i) { switch (i) { case (uint)int.MaxValue: case (uint)int.MaxValue + (uint)1: case (uint)int.MaxValue + (uint)2: case (uint)int.MaxValue + (uint)3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x7fffffff IL_0006: sub IL_0007: ldc.i4.3 IL_0008: bgt.un.s IL_000c IL_000a: ldc.i4.1 IL_000b: ret IL_000c: ldc.i4.0 IL_000d: ret }" ); } [Fact] public void DegenerateSwitch009() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(uint.MaxValue); Console.Write(ret); return(ret); } public static int M(uint i) { switch (i) { case 0: case 1: case uint.MaxValue: case uint.MaxValue - 1: case uint.MaxValue - 2: case uint.MaxValue - 3: return 1; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); compVerifier.VerifyIL("Test.M", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ble.un.s IL_000b IL_0004: ldarg.0 IL_0005: ldc.i4.s -4 IL_0007: sub IL_0008: ldc.i4.3 IL_0009: bgt.un.s IL_000d IL_000b: ldc.i4.1 IL_000c: ret IL_000d: ldc.i4.0 IL_000e: ret }" ); } [Fact] public void ByteTypeSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; ret = DoByte(); return(ret); } private static int DoByte() { int ret = 2; byte b = 2; switch (b) { case 1: case 2: ret--; break; case 3: break; default: break; } switch (b) { case 1: case 3: break; default: ret--; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoByte", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, //ret byte V_1) //b IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloc.1 IL_0005: ldc.i4.1 IL_0006: sub IL_0007: ldc.i4.1 IL_0008: ble.un.s IL_0010 IL_000a: ldloc.1 IL_000b: ldc.i4.3 IL_000c: beq.s IL_0014 IL_000e: br.s IL_0014 IL_0010: ldloc.0 IL_0011: ldc.i4.1 IL_0012: sub IL_0013: stloc.0 IL_0014: ldloc.1 IL_0015: ldc.i4.1 IL_0016: beq.s IL_0020 IL_0018: ldloc.1 IL_0019: ldc.i4.3 IL_001a: beq.s IL_0020 IL_001c: ldloc.0 IL_001d: ldc.i4.1 IL_001e: sub IL_001f: stloc.0 IL_0020: ldloc.0 IL_0021: call ""void System.Console.Write(int)"" IL_0026: ldloc.0 IL_0027: ret }" ); } [Fact] public void LongTypeSwitchArgumentExpression() { var text = @" using System; public class Test { public static void Main(string [] args) { int ret = 0; ret = DoLong(2); Console.Write(ret); ret = DoLong(4); Console.Write(ret); ret = DoLong(42); Console.Write(ret); } private static int DoLong(long b) { int ret = 2; switch (b) { case 1: ret++; break; case 2: ret--; break; case 3: break; case 4: ret += 7; break; default: ret+=2; break; } return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "194"); compVerifier.VerifyIL("Test.DoLong", @" { // Code size 62 (0x3e) .maxstack 3 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldc.i4.1 IL_0004: conv.i8 IL_0005: sub IL_0006: dup IL_0007: ldc.i4.3 IL_0008: conv.i8 IL_0009: ble.un.s IL_000e IL_000b: pop IL_000c: br.s IL_0038 IL_000e: conv.u4 IL_000f: switch ( IL_0026, IL_002c, IL_003c, IL_0032) IL_0024: br.s IL_0038 IL_0026: ldloc.0 IL_0027: ldc.i4.1 IL_0028: add IL_0029: stloc.0 IL_002a: br.s IL_003c IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: sub IL_002f: stloc.0 IL_0030: br.s IL_003c IL_0032: ldloc.0 IL_0033: ldc.i4.7 IL_0034: add IL_0035: stloc.0 IL_0036: br.s IL_003c IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: add IL_003b: stloc.0 IL_003c: ldloc.0 IL_003d: ret }" ); } [WorkItem(740058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740058")] [Fact] public void LongTypeSwitchArgumentExpressionOverflow() { var text = @" using System; public class Test { public static void Main(string[] args) { string ret; ret = DoLong(long.MaxValue); Console.Write(ret); ret = DoLong(long.MinValue); Console.Write(ret); ret = DoLong(1L); Console.Write(ret); ret = DoLong(0L); Console.Write(ret); } private static string DoLong(long b) { switch (b) { case long.MaxValue: return ""max""; case 1L: return ""one""; case long.MinValue: return ""min""; default: return ""default""; } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "maxminonedefault"); compVerifier.VerifyIL("Test.DoLong", @" { // Code size 53 (0x35) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i8 0x8000000000000000 IL_000a: beq.s IL_0029 IL_000c: ldarg.0 IL_000d: ldc.i4.1 IL_000e: conv.i8 IL_000f: beq.s IL_0023 IL_0011: ldarg.0 IL_0012: ldc.i8 0x7fffffffffffffff IL_001b: bne.un.s IL_002f IL_001d: ldstr ""max"" IL_0022: ret IL_0023: ldstr ""one"" IL_0028: ret IL_0029: ldstr ""min"" IL_002e: ret IL_002f: ldstr ""default"" IL_0034: ret }" ); } [Fact] public void ULongTypeSwitchArgumentExpression() { var text = @" using System; public class Test { public static void Main(string[] args) { int ret = 0; ret = DoULong(0x1000000000000001L); Console.Write(ret); } private static int DoULong(ulong b) { int ret = 2; switch (b) { case 0: ret++; break; case 1: ret--; break; case 2: break; case 3: ret += 7; break; default: ret += 40; break; } return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "42"); compVerifier.VerifyIL("Test.DoULong", @" { // Code size 60 (0x3c) .maxstack 3 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: dup IL_0004: ldc.i4.3 IL_0005: conv.i8 IL_0006: ble.un.s IL_000b IL_0008: pop IL_0009: br.s IL_0035 IL_000b: conv.u4 IL_000c: switch ( IL_0023, IL_0029, IL_003a, IL_002f) IL_0021: br.s IL_0035 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: br.s IL_003a IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: sub IL_002c: stloc.0 IL_002d: br.s IL_003a IL_002f: ldloc.0 IL_0030: ldc.i4.7 IL_0031: add IL_0032: stloc.0 IL_0033: br.s IL_003a IL_0035: ldloc.0 IL_0036: ldc.i4.s 40 IL_0038: add IL_0039: stloc.0 IL_003a: ldloc.0 IL_003b: ret }" ); } [Fact] public void EnumTypeSwitchArgumentExpressionWithCasts() { var text = @"using System; public class Test { enum eTypes { kFirst, kSecond, kThird, }; public static int Main(string [] args) { int ret = 0; ret = DoEnum(); return(ret); } private static int DoEnum() { int ret = 2; eTypes e = eTypes.kSecond; switch (e) { case eTypes.kThird: case eTypes.kSecond: ret--; break; case (eTypes) (-1): break; default: break; } switch (e) { case (eTypes)100: case (eTypes) (-1): break; default: ret--; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoEnum", @" { // Code size 39 (0x27) .maxstack 2 .locals init (int V_0, //ret Test.eTypes V_1) //e IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldloc.1 IL_0005: ldc.i4.m1 IL_0006: beq.s IL_0012 IL_0008: ldloc.1 IL_0009: ldc.i4.1 IL_000a: sub IL_000b: ldc.i4.1 IL_000c: bgt.un.s IL_0012 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: sub IL_0011: stloc.0 IL_0012: ldloc.1 IL_0013: ldc.i4.m1 IL_0014: beq.s IL_001f IL_0016: ldloc.1 IL_0017: ldc.i4.s 100 IL_0019: beq.s IL_001f IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: sub IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldloc.0 IL_0026: ret }" ); } [Fact] public void NullableEnumTypeSwitchArgumentExpression() { var text = @"using System; public class Test { enum eTypes { kFirst, kSecond, kThird, }; public static int Main(string [] args) { int ret = 0; ret = DoEnum(); return(ret); } private static int DoEnum() { int ret = 3; eTypes? e = eTypes.kSecond; switch (e) { case eTypes.kThird: case eTypes.kSecond: ret--; break; default: break; } switch (e) { case null: case (eTypes) (-1): break; default: ret--; break; } e = null; switch (e) { case null: ret--; break; case (eTypes) (-1): case eTypes.kThird: case eTypes.kSecond: default: break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.DoEnum", @" { // Code size 109 (0x6d) .maxstack 2 .locals init (int V_0, //ret Test.eTypes? V_1, //e Test.eTypes V_2) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: call ""Test.eTypes?..ctor(Test.eTypes)"" IL_000a: ldloca.s V_1 IL_000c: call ""bool Test.eTypes?.HasValue.get"" IL_0011: brfalse.s IL_0025 IL_0013: ldloca.s V_1 IL_0015: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_001a: stloc.2 IL_001b: ldloc.2 IL_001c: ldc.i4.1 IL_001d: sub IL_001e: ldc.i4.1 IL_001f: bgt.un.s IL_0025 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: sub IL_0024: stloc.0 IL_0025: ldloca.s V_1 IL_0027: call ""bool Test.eTypes?.HasValue.get"" IL_002c: brfalse.s IL_003c IL_002e: ldloca.s V_1 IL_0030: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_0035: ldc.i4.m1 IL_0036: beq.s IL_003c IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: sub IL_003b: stloc.0 IL_003c: ldloca.s V_1 IL_003e: initobj ""Test.eTypes?"" IL_0044: ldloca.s V_1 IL_0046: call ""bool Test.eTypes?.HasValue.get"" IL_004b: brfalse.s IL_0061 IL_004d: ldloca.s V_1 IL_004f: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()"" IL_0054: stloc.2 IL_0055: ldloc.2 IL_0056: ldc.i4.m1 IL_0057: beq.s IL_0065 IL_0059: ldloc.2 IL_005a: ldc.i4.1 IL_005b: sub IL_005c: ldc.i4.1 IL_005d: ble.un.s IL_0065 IL_005f: br.s IL_0065 IL_0061: ldloc.0 IL_0062: ldc.i4.1 IL_0063: sub IL_0064: stloc.0 IL_0065: ldloc.0 IL_0066: call ""void System.Console.Write(int)"" IL_006b: ldloc.0 IL_006c: ret }"); } [Fact] public void SwitchSectionWithGotoNonSwitchLabel() { var text = @" class Test { public static int Main() { int ret = 1; switch (10) { case 123: // No unreachable code warning here mylabel: --ret; break; case 9: // No unreachable code warning here case 10: case 11: // No unreachable code warning here goto mylabel; } System.Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics(); compVerifier.VerifyIL("Test.Main", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""void System.Console.Write(int)"" IL_000c: ldloc.0 IL_000d: ret }" ); } [Fact] public void SwitchSectionWithGotoNonSwitchLabel_02() { var text = @"class Test { delegate void D(); public static void Main() { int i = 0; switch (10) { case 5: goto mylabel; case 10: goto case 5; case 15: mylabel: D d1 = delegate() { System.Console.Write(i); }; d1(); return; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (Test.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Test.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld ""int Test.<>c__DisplayClass1_0.i"" IL_000d: ldloc.0 IL_000e: ldftn ""void Test.<>c__DisplayClass1_0.<Main>b__0()"" IL_0014: newobj ""Test.D..ctor(object, System.IntPtr)"" IL_0019: callvirt ""void Test.D.Invoke()"" IL_001e: ret } " ); } [Fact] public void SwitchSectionWithReturnStatement() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 3; for (int i = 0; i < 3; i++) { switch (i) { case 1: case 0: case 2: ret--; break; default: Console.Write(1); return(1); } } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, //ret int V_1) //i IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_001c IL_0006: ldloc.1 IL_0007: ldc.i4.2 IL_0008: bgt.un.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: sub IL_000d: stloc.0 IL_000e: br.s IL_0018 IL_0010: ldc.i4.1 IL_0011: call ""void System.Console.Write(int)"" IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldloc.1 IL_0019: ldc.i4.1 IL_001a: add IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.3 IL_001e: blt.s IL_0006 IL_0020: ldloc.0 IL_0021: call ""void System.Console.Write(int)"" IL_0026: ldloc.0 IL_0027: ret }" ); } [Fact] public void SwitchSectionWithReturnStatement_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case 1: return 1; } return 0; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_0006 IL_0004: ldc.i4.1 IL_0005: ret IL_0006: ldc.i4.0 IL_0007: ret }" ); } [Fact] public void CaseLabelWithTypeCastToGoverningType() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 5; switch (i) { case (int) 5.0f: return 0; default: return 1; } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.5 IL_0002: bne.un.s IL_0006 IL_0004: ldc.i4.0 IL_0005: ret IL_0006: ldc.i4.1 IL_0007: ret }" ); } [Fact] public void SwitchSectionWithTryFinally() { var text = @"using System; class Class1 { static int Main() { int j = 0; int i = 3; switch (j) { case 0: try { i = 0; } catch { i = 1; } finally { j = 2; } break; default: i = 2; break; } Console.Write(i); return i; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Class1.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: ldc.i4.3 IL_0002: stloc.0 IL_0003: brtrue.s IL_0010 IL_0005: nop .try { .try { IL_0006: ldc.i4.0 IL_0007: stloc.0 IL_0008: leave.s IL_0012 } catch object { IL_000a: pop IL_000b: ldc.i4.1 IL_000c: stloc.0 IL_000d: leave.s IL_0012 } } finally { IL_000f: endfinally } IL_0010: ldc.i4.2 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ret }" ); } [Fact] public void MultipleSwitchSectionsWithGotoCase() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int ret = 6; switch (ret) { case 0: ret--; // 2 Console.Write(""case 0: ""); Console.WriteLine(ret); goto case 9999; case 2: ret--; // 4 Console.Write(""case 2: ""); Console.WriteLine(ret); goto case 255; case 6: // start here ret--; // 5 Console.Write(""case 5: ""); Console.WriteLine(ret); goto case 2; case 9999: ret--; // 1 Console.Write(""case 9999: ""); Console.WriteLine(ret); goto default; case 0xff: ret--; // 3 Console.Write(""case 0xff: ""); Console.WriteLine(ret); goto case 0; default: ret--; Console.Write(""Default: ""); Console.WriteLine(ret); if (ret > 0) { goto case -1; } break; case -1: ret = 999; Console.WriteLine(""case -1: ""); Console.Write(ret); break; } return(ret); } }"; string expectedOutput = @"case 5: 5 case 2: 4 case 0xff: 3 case 0: 2 case 9999: 1 Default: 0 0"; var compVerifier = CompileAndVerify(text, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.M", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (int V_0) //ret IL_0000: ldc.i4.6 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.6 IL_0004: bgt.s IL_0027 IL_0006: ldloc.0 IL_0007: ldc.i4.m1 IL_0008: sub IL_0009: switch ( IL_00bf, IL_0039, IL_00a7, IL_004f) IL_001e: ldloc.0 IL_001f: ldc.i4.6 IL_0020: beq.s IL_0065 IL_0022: br IL_00a7 IL_0027: ldloc.0 IL_0028: ldc.i4 0xff IL_002d: beq.s IL_0091 IL_002f: ldloc.0 IL_0030: ldc.i4 0x270f IL_0035: beq.s IL_007b IL_0037: br.s IL_00a7 IL_0039: ldloc.0 IL_003a: ldc.i4.1 IL_003b: sub IL_003c: stloc.0 IL_003d: ldstr ""case 0: "" IL_0042: call ""void System.Console.Write(string)"" IL_0047: ldloc.0 IL_0048: call ""void System.Console.WriteLine(int)"" IL_004d: br.s IL_007b IL_004f: ldloc.0 IL_0050: ldc.i4.1 IL_0051: sub IL_0052: stloc.0 IL_0053: ldstr ""case 2: "" IL_0058: call ""void System.Console.Write(string)"" IL_005d: ldloc.0 IL_005e: call ""void System.Console.WriteLine(int)"" IL_0063: br.s IL_0091 IL_0065: ldloc.0 IL_0066: ldc.i4.1 IL_0067: sub IL_0068: stloc.0 IL_0069: ldstr ""case 5: "" IL_006e: call ""void System.Console.Write(string)"" IL_0073: ldloc.0 IL_0074: call ""void System.Console.WriteLine(int)"" IL_0079: br.s IL_004f IL_007b: ldloc.0 IL_007c: ldc.i4.1 IL_007d: sub IL_007e: stloc.0 IL_007f: ldstr ""case 9999: "" IL_0084: call ""void System.Console.Write(string)"" IL_0089: ldloc.0 IL_008a: call ""void System.Console.WriteLine(int)"" IL_008f: br.s IL_00a7 IL_0091: ldloc.0 IL_0092: ldc.i4.1 IL_0093: sub IL_0094: stloc.0 IL_0095: ldstr ""case 0xff: "" IL_009a: call ""void System.Console.Write(string)"" IL_009f: ldloc.0 IL_00a0: call ""void System.Console.WriteLine(int)"" IL_00a5: br.s IL_0039 IL_00a7: ldloc.0 IL_00a8: ldc.i4.1 IL_00a9: sub IL_00aa: stloc.0 IL_00ab: ldstr ""Default: "" IL_00b0: call ""void System.Console.Write(string)"" IL_00b5: ldloc.0 IL_00b6: call ""void System.Console.WriteLine(int)"" IL_00bb: ldloc.0 IL_00bc: ldc.i4.0 IL_00bd: ble.s IL_00d5 IL_00bf: ldc.i4 0x3e7 IL_00c4: stloc.0 IL_00c5: ldstr ""case -1: "" IL_00ca: call ""void System.Console.WriteLine(string)"" IL_00cf: ldloc.0 IL_00d0: call ""void System.Console.Write(int)"" IL_00d5: ldloc.0 IL_00d6: ret }" ); } [Fact] public void Switch_TestSwitchBuckets_01() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 0; // Expected switch buckets: (10, 12, 14) (1000) (2000, 2001, 2005, 2008, 2009, 2010) switch (i) { case 10: case 2000: case 12: return 1; case 2001: case 14: return 2; case 1000: case 2010: case 2008: return 3; case 2005: case 2009: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 107 (0x6b) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.s 10 IL_0005: sub IL_0006: switch ( IL_0061, IL_0069, IL_0061, IL_0069, IL_0063) IL_001f: ldloc.0 IL_0020: ldc.i4 0x3e8 IL_0025: beq.s IL_0065 IL_0027: ldloc.0 IL_0028: ldc.i4 0x7d0 IL_002d: sub IL_002e: switch ( IL_0061, IL_0063, IL_0069, IL_0069, IL_0069, IL_0067, IL_0069, IL_0069, IL_0065, IL_0067, IL_0065) IL_005f: br.s IL_0069 IL_0061: ldc.i4.1 IL_0062: ret IL_0063: ldc.i4.2 IL_0064: ret IL_0065: ldc.i4.3 IL_0066: ret IL_0067: ldc.i4.2 IL_0068: ret IL_0069: ldc.i4.0 IL_006a: ret }" ); } [Fact] public void Switch_TestSwitchBuckets_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { int i = 0; // Expected switch buckets: (10, 12, 14) (1000) (2000, 2001) (2008, 2009, 2010) switch (i) { case 10: case 2000: case 12: return 1; case 2001: case 14: return 2; case 1000: case 2010: case 2008: return 3; case 2009: return 2; } return 0; } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.M", @" { // Code size 101 (0x65) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4 0x3e8 IL_0008: bgt.s IL_0031 IL_000a: ldloc.0 IL_000b: ldc.i4.s 10 IL_000d: sub IL_000e: switch ( IL_005b, IL_0063, IL_005b, IL_0063, IL_005d) IL_0027: ldloc.0 IL_0028: ldc.i4 0x3e8 IL_002d: beq.s IL_005f IL_002f: br.s IL_0063 IL_0031: ldloc.0 IL_0032: ldc.i4 0x7d0 IL_0037: beq.s IL_005b IL_0039: ldloc.0 IL_003a: ldc.i4 0x7d1 IL_003f: beq.s IL_005d IL_0041: ldloc.0 IL_0042: ldc.i4 0x7d8 IL_0047: sub IL_0048: switch ( IL_005f, IL_0061, IL_005f) IL_0059: br.s IL_0063 IL_005b: ldc.i4.1 IL_005c: ret IL_005d: ldc.i4.2 IL_005e: ret IL_005f: ldc.i4.3 IL_0060: ret IL_0061: ldc.i4.2 IL_0062: ret IL_0063: ldc.i4.0 IL_0064: ret }" ); } [WorkItem(542398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542398")] [Fact] public void MaxValueGotoCaseExpression() { var text = @" class Program { static void Main(string[] args) { ulong a = 0; switch (a) { case long.MaxValue: goto case ulong.MaxValue; case ulong.MaxValue: break; } } } "; CompileAndVerify(text, expectedOutput: ""); } [WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")] [Fact()] public void NullableAsSwitchExpression() { var text = @"using System; class Program { static void Main() { sbyte? local = null; switch (local) { case null: Console.Write(""null ""); break; case 1: Console.Write(""1 ""); break; } Goo(1); } static void Goo(sbyte? p) { switch (p) { case 1: Console.Write(""1 ""); break; case null: Console.Write(""null ""); break; } } } "; var verifier = CompileAndVerify(text, expectedOutput: "null 1"); verifier.VerifyIL("Program.Main", @" { // Code size 64 (0x40) .maxstack 2 .locals init (sbyte? V_0) //local IL_0000: ldloca.s V_0 IL_0002: initobj ""sbyte?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool sbyte?.HasValue.get"" IL_000f: brfalse.s IL_001d IL_0011: ldloca.s V_0 IL_0013: call ""sbyte sbyte?.GetValueOrDefault()"" IL_0018: ldc.i4.1 IL_0019: beq.s IL_0029 IL_001b: br.s IL_0033 IL_001d: ldstr ""null "" IL_0022: call ""void System.Console.Write(string)"" IL_0027: br.s IL_0033 IL_0029: ldstr ""1 "" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldc.i4.1 IL_0034: conv.i1 IL_0035: newobj ""sbyte?..ctor(sbyte)"" IL_003a: call ""void Program.Goo(sbyte?)"" IL_003f: ret }"); } [WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")] [Fact()] public void NullableAsSwitchExpression_02() { var text = @"using System; class Program { static void Main() { Goo(null); Goo(100); } static void Goo(short? p) { switch (p) { case null: Console.Write(""null ""); break; case 1: break; case 2: break; case 3: break; case 100: Console.Write(""100 ""); break; case 101: break; case 103: break; case 1001: break; case 1002: break; case 1003: break; } switch (p) { case 1: break; case 2: break; case 3: break; case 101: break; case 103: break; case 1001: break; case 1002: break; case 1003: break; default: Console.Write(""default ""); break; } switch (p) { case 1: Console.Write(""FAIL""); break; case 2: Console.Write(""FAIL""); break; case 3: Console.Write(""FAIL""); break; case 101: Console.Write(""FAIL""); break; case 103: Console.Write(""FAIL""); break; case 1001: Console.Write(""FAIL""); break; case 1002: Console.Write(""FAIL""); break; case 1003: Console.Write(""FAIL""); break; } } } "; var verifier = CompileAndVerify(text, expectedOutput: "null default 100 default "); verifier.VerifyIL("Program.Goo", @" { // Code size 367 (0x16f) .maxstack 2 .locals init (short V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool short?.HasValue.get"" IL_0007: brfalse.s IL_0058 IL_0009: ldarga.s V_0 IL_000b: call ""short short?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldc.i4.1 IL_0013: sub IL_0014: switch ( IL_006e, IL_006e, IL_006e) IL_0025: ldloc.0 IL_0026: ldc.i4.s 100 IL_0028: sub IL_0029: switch ( IL_0064, IL_006e, IL_006e, IL_006e) IL_003e: ldloc.0 IL_003f: ldc.i4 0x3e9 IL_0044: sub IL_0045: switch ( IL_006e, IL_006e, IL_006e) IL_0056: br.s IL_006e IL_0058: ldstr ""null "" IL_005d: call ""void System.Console.Write(string)"" IL_0062: br.s IL_006e IL_0064: ldstr ""100 "" IL_0069: call ""void System.Console.Write(string)"" IL_006e: ldarga.s V_0 IL_0070: call ""bool short?.HasValue.get"" IL_0075: brfalse.s IL_00bc IL_0077: ldarga.s V_0 IL_0079: call ""short short?.GetValueOrDefault()"" IL_007e: stloc.0 IL_007f: ldloc.0 IL_0080: ldc.i4.s 101 IL_0082: bgt.s IL_009f IL_0084: ldloc.0 IL_0085: ldc.i4.1 IL_0086: sub IL_0087: switch ( IL_00c6, IL_00c6, IL_00c6) IL_0098: ldloc.0 IL_0099: ldc.i4.s 101 IL_009b: beq.s IL_00c6 IL_009d: br.s IL_00bc IL_009f: ldloc.0 IL_00a0: ldc.i4.s 103 IL_00a2: beq.s IL_00c6 IL_00a4: ldloc.0 IL_00a5: ldc.i4 0x3e9 IL_00aa: sub IL_00ab: switch ( IL_00c6, IL_00c6, IL_00c6) IL_00bc: ldstr ""default "" IL_00c1: call ""void System.Console.Write(string)"" IL_00c6: ldarga.s V_0 IL_00c8: call ""bool short?.HasValue.get"" IL_00cd: brfalse IL_016e IL_00d2: ldarga.s V_0 IL_00d4: call ""short short?.GetValueOrDefault()"" IL_00d9: stloc.0 IL_00da: ldloc.0 IL_00db: ldc.i4.s 101 IL_00dd: bgt.s IL_00f9 IL_00df: ldloc.0 IL_00e0: ldc.i4.1 IL_00e1: sub IL_00e2: switch ( IL_0117, IL_0122, IL_012d) IL_00f3: ldloc.0 IL_00f4: ldc.i4.s 101 IL_00f6: beq.s IL_0138 IL_00f8: ret IL_00f9: ldloc.0 IL_00fa: ldc.i4.s 103 IL_00fc: beq.s IL_0143 IL_00fe: ldloc.0 IL_00ff: ldc.i4 0x3e9 IL_0104: sub IL_0105: switch ( IL_014e, IL_0159, IL_0164) IL_0116: ret IL_0117: ldstr ""FAIL"" IL_011c: call ""void System.Console.Write(string)"" IL_0121: ret IL_0122: ldstr ""FAIL"" IL_0127: call ""void System.Console.Write(string)"" IL_012c: ret IL_012d: ldstr ""FAIL"" IL_0132: call ""void System.Console.Write(string)"" IL_0137: ret IL_0138: ldstr ""FAIL"" IL_013d: call ""void System.Console.Write(string)"" IL_0142: ret IL_0143: ldstr ""FAIL"" IL_0148: call ""void System.Console.Write(string)"" IL_014d: ret IL_014e: ldstr ""FAIL"" IL_0153: call ""void System.Console.Write(string)"" IL_0158: ret IL_0159: ldstr ""FAIL"" IL_015e: call ""void System.Console.Write(string)"" IL_0163: ret IL_0164: ldstr ""FAIL"" IL_0169: call ""void System.Console.Write(string)"" IL_016e: ret }"); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableInt64WithInt32Label() { var text = @"public static class C { public static bool F(long? x) { switch (x) { case 1: return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "True"); compVerifier.VerifyIL("C.F(long?)", @"{ // Code size 24 (0x18) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool long?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""long long?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: conv.i8 IL_0012: bne.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableWithNonConstant() { var text = @"public static class C { public static bool F(int? x) { int i = 4; switch (x) { case i: return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compilation = base.CreateCSharpCompilation(text); compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case i: Diagnostic(ErrorCode.ERR_ConstantExpected, "i").WithLocation(8, 18) ); } [Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")] public void SwitchOnNullableWithNonCompatibleType() { var text = @"public static class C { public static bool F(int? x) { switch (x) { case default(System.DateTime): return true; default: return false; } } static void Main() { System.Console.WriteLine(F(1)); } }"; var compilation = base.CreateCSharpCompilation(text); // (7,18): error CS0029: Cannot implicitly convert type 'System.DateTime' to 'int?' // case default(System.DateTime): var expected = Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(System.DateTime)").WithArguments("System.DateTime", "int?"); compilation.VerifyDiagnostics(expected); } [Fact] public void SwitchOnNullableInt64WithInt32LabelWithEnum() { var text = @"public static class C { public static bool F(long? x) { switch (x) { case (int)Goo.X: return true; default: return false; } } public enum Goo : int { X = 1 } static void Main() { System.Console.WriteLine(F(1)); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "True"); compVerifier.VerifyIL("C.F(long?)", @"{ // Code size 24 (0x18) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: call ""bool long?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""long long?.GetValueOrDefault()"" IL_0010: ldc.i4.1 IL_0011: conv.i8 IL_0012: bne.un.s IL_0016 IL_0014: ldc.i4.1 IL_0015: ret IL_0016: ldc.i4.0 IL_0017: ret }" ); } // TODO: Add more targeted tests for verifying switch bucketing #region "String tests" [Fact] public void StringTypeSwitchArgumentExpression() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { string s = ""hello""; switch (s) { default: return 1; case null: return 1; case ""hello"": return 0; } return 1; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (25,5): warning CS0162: Unreachable code detected // return 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); compVerifier.VerifyIL("Test.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //s IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0018 IL_0009: ldloc.0 IL_000a: ldstr ""hello"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_001a IL_0016: ldc.i4.1 IL_0017: ret IL_0018: ldc.i4.1 IL_0019: ret IL_001a: ldc.i4.0 IL_001b: ret }" ); // We shouldn't generate a string hash synthesized method if we are generating non hash string switch VerifySynthesizedStringHashMethod(compVerifier, expected: false); } [Fact] public void StringSwitch_SwitchOnNull() { var text = @"using System; public class Test { public static int Main(string[] args) { string s = null; int ret = 0; switch (s) { case null + ""abc"": ret = 1; break; case null + ""def"": ret = 1; break; } Console.Write(ret); return ret; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("Test.Main", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (string V_0, //s int V_1) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldstr ""abc"" IL_000a: call ""bool string.op_Equality(string, string)"" IL_000f: brtrue.s IL_0020 IL_0011: ldloc.0 IL_0012: ldstr ""def"" IL_0017: call ""bool string.op_Equality(string, string)"" IL_001c: brtrue.s IL_0024 IL_001e: br.s IL_0026 IL_0020: ldc.i4.1 IL_0021: stloc.1 IL_0022: br.s IL_0026 IL_0024: ldc.i4.1 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldloc.1 IL_002d: ret }" ); // We shouldn't generate a string hash synthesized method if we are generating non hash string switch VerifySynthesizedStringHashMethod(compVerifier, expected: false); } [Fact] [WorkItem(546632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546632")] public void StringSwitch_HashTableSwitch_01() { var text = @"using System; class Test { public static bool M(string test) { string value = """"; if (test != null && test.IndexOf(""C#"") != -1) test = test.Remove(0, 2); switch (test) { case null: value = null; break; case """": break; case ""_"": value = ""_""; break; case ""W"": value = ""W""; break; case ""B"": value = ""B""; break; case ""C"": value = ""C""; break; case ""<"": value = ""<""; break; case ""T"": value = ""T""; break; case ""M"": value = ""M""; break; } return (value == test); } public static void Main() { bool success = Test.M(""C#""); success &= Test.M(""C#_""); success &= Test.M(""C#W""); success &= Test.M(""C#B""); success &= Test.M(""C#C""); success &= Test.M(""C#<""); success &= Test.M(""C#T""); success &= Test.M(""C#M""); success &= Test.M(null); Console.WriteLine(success); } }"; var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "True"); compVerifier.VerifyIL("Test.M", @" { // Code size 365 (0x16d) .maxstack 3 .locals init (string V_0, //value uint V_1) IL_0000: ldstr """" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: brfalse.s IL_0021 IL_0009: ldarg.0 IL_000a: ldstr ""C#"" IL_000f: callvirt ""int string.IndexOf(string)"" IL_0014: ldc.i4.m1 IL_0015: beq.s IL_0021 IL_0017: ldarg.0 IL_0018: ldc.i4.0 IL_0019: ldc.i4.2 IL_001a: callvirt ""string string.Remove(int, int)"" IL_001f: starg.s V_0 IL_0021: ldarg.0 IL_0022: brfalse IL_012b IL_0027: ldarg.0 IL_0028: call ""ComputeStringHash"" IL_002d: stloc.1 IL_002e: ldloc.1 IL_002f: ldc.i4 0xc70bfb85 IL_0034: bgt.un.s IL_006e IL_0036: ldloc.1 IL_0037: ldc.i4 0x811c9dc5 IL_003c: bgt.un.s IL_0056 IL_003e: ldloc.1 IL_003f: ldc.i4 0x390caefb IL_0044: beq IL_00fe IL_0049: ldloc.1 IL_004a: ldc.i4 0x811c9dc5 IL_004f: beq.s IL_00a6 IL_0051: br IL_0165 IL_0056: ldloc.1 IL_0057: ldc.i4 0xc60bf9f2 IL_005c: beq IL_00ef IL_0061: ldloc.1 IL_0062: ldc.i4 0xc70bfb85 IL_0067: beq.s IL_00e0 IL_0069: br IL_0165 IL_006e: ldloc.1 IL_006f: ldc.i4 0xd10c0b43 IL_0074: bgt.un.s IL_0091 IL_0076: ldloc.1 IL_0077: ldc.i4 0xc80bfd18 IL_007c: beq IL_011c IL_0081: ldloc.1 IL_0082: ldc.i4 0xd10c0b43 IL_0087: beq IL_010d IL_008c: br IL_0165 IL_0091: ldloc.1 IL_0092: ldc.i4 0xd20c0cd6 IL_0097: beq.s IL_00ce IL_0099: ldloc.1 IL_009a: ldc.i4 0xda0c196e IL_009f: beq.s IL_00bc IL_00a1: br IL_0165 IL_00a6: ldarg.0 IL_00a7: brfalse IL_0165 IL_00ac: ldarg.0 IL_00ad: call ""int string.Length.get"" IL_00b2: brfalse IL_0165 IL_00b7: br IL_0165 IL_00bc: ldarg.0 IL_00bd: ldstr ""_"" IL_00c2: call ""bool string.op_Equality(string, string)"" IL_00c7: brtrue.s IL_012f IL_00c9: br IL_0165 IL_00ce: ldarg.0 IL_00cf: ldstr ""W"" IL_00d4: call ""bool string.op_Equality(string, string)"" IL_00d9: brtrue.s IL_0137 IL_00db: br IL_0165 IL_00e0: ldarg.0 IL_00e1: ldstr ""B"" IL_00e6: call ""bool string.op_Equality(string, string)"" IL_00eb: brtrue.s IL_013f IL_00ed: br.s IL_0165 IL_00ef: ldarg.0 IL_00f0: ldstr ""C"" IL_00f5: call ""bool string.op_Equality(string, string)"" IL_00fa: brtrue.s IL_0147 IL_00fc: br.s IL_0165 IL_00fe: ldarg.0 IL_00ff: ldstr ""<"" IL_0104: call ""bool string.op_Equality(string, string)"" IL_0109: brtrue.s IL_014f IL_010b: br.s IL_0165 IL_010d: ldarg.0 IL_010e: ldstr ""T"" IL_0113: call ""bool string.op_Equality(string, string)"" IL_0118: brtrue.s IL_0157 IL_011a: br.s IL_0165 IL_011c: ldarg.0 IL_011d: ldstr ""M"" IL_0122: call ""bool string.op_Equality(string, string)"" IL_0127: brtrue.s IL_015f IL_0129: br.s IL_0165 IL_012b: ldnull IL_012c: stloc.0 IL_012d: br.s IL_0165 IL_012f: ldstr ""_"" IL_0134: stloc.0 IL_0135: br.s IL_0165 IL_0137: ldstr ""W"" IL_013c: stloc.0 IL_013d: br.s IL_0165 IL_013f: ldstr ""B"" IL_0144: stloc.0 IL_0145: br.s IL_0165 IL_0147: ldstr ""C"" IL_014c: stloc.0 IL_014d: br.s IL_0165 IL_014f: ldstr ""<"" IL_0154: stloc.0 IL_0155: br.s IL_0165 IL_0157: ldstr ""T"" IL_015c: stloc.0 IL_015d: br.s IL_0165 IL_015f: ldstr ""M"" IL_0164: stloc.0 IL_0165: ldloc.0 IL_0166: ldarg.0 IL_0167: call ""bool string.op_Equality(string, string)"" IL_016c: ret }" ); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); // verify that hash method is internal: var reference = compVerifier.Compilation.EmitToImageReference(); var comp = CSharpCompilation.Create("Name", references: new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var pid = ((NamedTypeSymbol)comp.GlobalNamespace.GetMembers().Single(s => s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); var member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single(); Assert.Equal(Accessibility.Internal, member.DeclaredAccessibility); } [Fact] public void StringSwitch_HashTableSwitch_02() { var text = @" using System; using System.Text; class Test { public static bool Switcheroo(string test) { string value = """"; if (test.IndexOf(""C#"") != -1) test = test.Remove(0, 2); switch (test) { case ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"": value = ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""; break; case ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"": value = ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""; break; case ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"": value = ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""; break; case ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"": value = ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""; break; case ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"": value = ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""; break; case ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"": value = ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""; break; case ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"": value = ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""; break; case ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"": value = ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""; break; case ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"": value = ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""; break; case ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"": value = ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""; break; case "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"": value = "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""; break; case ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"": value = ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""; break; case ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"": value = ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""; break; case ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"": value = ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""; break; case ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"": value = ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""; break; case ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"": value = ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""; break; case ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"": value = ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""; break; case ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"": value = ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""; break; case ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"": value = ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""; break; case ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"": value = ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""; break; case ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"": value = ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""; break; case ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"": value = ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""; break; case ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"": value = ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""; break; case ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"": value = ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""; break; } return (value == test); } public static void Main() { string status = ""PASS""; bool retval; retval = Test.Switcheroo(""C#N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#>AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""); if (!retval) status = ""FAIL""; retval = Test.Switcheroo(""C#a@=FkgImdk5<Wn0DRYa?m0<F0JT4kha;H:HIZ;6C""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Zbk^]59O<<GHe8MjRMOh4]c3@RQ?hU>^G81cOMW:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#hP<l25H@W60UF4bYYDU]0AjIE6oCQ^k66F9gNJ`Q""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#XS9dCIb;9T`;JJ1Jmimba@@0[l[B=BgDhKZ05DO2""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#JbMbko?;e@1XLU>:=c_Vg>0YTJ7Qd]6KLh26miBV""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#IW3:>L<H<kf:AS2ZYDGaE`?^HZY_D]cRO[lNjd4;""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#NC>J^E3;VJ`nKSjVbJ_Il^^@0Xof9CFA2I1I^9c>""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#TfjQOCnAhM8[T3JUbLlQMS=`F=?:FPT3=X0Q]aj:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#H_6fHA8OKO><TYDXiIg[Qed<=71KC>^6cTMOjT]d""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#jN>cSCF0?I<1RSQ^g^HnBABPhUc>5Y`ahlY9HS]5""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#V;`Q_kEGIX=Mh9=UVF[Q@Q=QTT@oC]IRF]<bA1R9""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#7DKT?2VIk2^XUJ>C]G_IDe?299DJTD>1RO18Ql>F""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#U`^]IeJC;o^90V=5<ToV<Gj26hnZLolffohc8iZX""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9S?>A?E>gBl_dC[iCiiNnW7<BP;eGHf>8ceTGZ6C""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#ALLhjN7]XVBBA=VcYM8iWg^FGiG[QG03dlKYnIAe""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#6<]i]EllPZf6mnAM0D1;0eP6_G1HmRSi?`1o[a_a""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#]5Tb^6:NB]>ahEoWI5U9N5beS<?da]A]fL08AelQ""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#KhPBV8=H?G^Hmaaf^n<GcoI8eC1O_0]579;MY=81""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#A8iN_OFUPIcWac0^LU1;^HaEX[_E]<8h3N:Hm_XX""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Y811aKWEJYcX6Y1aj_I]O7TXP5j_lo;71kAiB:;:""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#P@ok2DgbUDeLVA:POd`B_S@2Ocg99VQBZ<LI<gd1""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#9V84FSRoD9453VdERM86a6B12VeN]hNNU:]XE`W9""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#Tegah0mKcWmFhaH0K0oSjKGkmH8gDEF3SBVd2H1P""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#=II;VADkVKf7JV55ca5oUjkPaWSY7`LXTlgTV4^W""); if (retval) status = ""FAIL""; retval = Test.Switcheroo(""C#k7XPoXNhd8P0V7@Sd5ohO>h7io3Pl[J[8g:[_da^""); if (retval) status = ""FAIL""; Console.Write(status); } }"; var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "PASS"); compVerifier.VerifyIL("Test.Switcheroo", @" { // Code size 1115 (0x45b) .maxstack 3 .locals init (string V_0, //value uint V_1) IL_0000: ldstr """" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldstr ""C#"" IL_000c: callvirt ""int string.IndexOf(string)"" IL_0011: ldc.i4.m1 IL_0012: beq.s IL_001e IL_0014: ldarg.0 IL_0015: ldc.i4.0 IL_0016: ldc.i4.2 IL_0017: callvirt ""string string.Remove(int, int)"" IL_001c: starg.s V_0 IL_001e: ldarg.0 IL_001f: call ""ComputeStringHash"" IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: ldc.i4 0xb2f29419 IL_002b: bgt.un IL_00e0 IL_0030: ldloc.1 IL_0031: ldc.i4 0x619348d8 IL_0036: bgt.un.s IL_008c IL_0038: ldloc.1 IL_0039: ldc.i4 0x36758e37 IL_003e: bgt.un.s IL_0066 IL_0040: ldloc.1 IL_0041: ldc.i4 0x144fd20d IL_0046: beq IL_02ae IL_004b: ldloc.1 IL_004c: ldc.i4 0x14ca99e2 IL_0051: beq IL_025a IL_0056: ldloc.1 IL_0057: ldc.i4 0x36758e37 IL_005c: beq IL_0206 IL_0061: br IL_0453 IL_0066: ldloc.1 IL_0067: ldc.i4 0x5398a778 IL_006c: beq IL_021b IL_0071: ldloc.1 IL_0072: ldc.i4 0x616477cf IL_0077: beq IL_01b2 IL_007c: ldloc.1 IL_007d: ldc.i4 0x619348d8 IL_0082: beq IL_02ed IL_0087: br IL_0453 IL_008c: ldloc.1 IL_008d: ldc.i4 0x78a826a8 IL_0092: bgt.un.s IL_00ba IL_0094: ldloc.1 IL_0095: ldc.i4 0x65b3e3e5 IL_009a: beq IL_02c3 IL_009f: ldloc.1 IL_00a0: ldc.i4 0x7822b5bc IL_00a5: beq IL_0284 IL_00aa: ldloc.1 IL_00ab: ldc.i4 0x78a826a8 IL_00b0: beq IL_01dc IL_00b5: br IL_0453 IL_00ba: ldloc.1 IL_00bb: ldc.i4 0x7f66da4e IL_00c0: beq IL_0356 IL_00c5: ldloc.1 IL_00c6: ldc.i4 0xb13d374d IL_00cb: beq IL_032c IL_00d0: ldloc.1 IL_00d1: ldc.i4 0xb2f29419 IL_00d6: beq IL_0302 IL_00db: br IL_0453 IL_00e0: ldloc.1 IL_00e1: ldc.i4 0xd59864f4 IL_00e6: bgt.un.s IL_013c IL_00e8: ldloc.1 IL_00e9: ldc.i4 0xbf4a9f8e IL_00ee: bgt.un.s IL_0116 IL_00f0: ldloc.1 IL_00f1: ldc.i4 0xb6e02d3a IL_00f6: beq IL_0299 IL_00fb: ldloc.1 IL_00fc: ldc.i4 0xbaed3db3 IL_0101: beq IL_0317 IL_0106: ldloc.1 IL_0107: ldc.i4 0xbf4a9f8e IL_010c: beq IL_0230 IL_0111: br IL_0453 IL_0116: ldloc.1 IL_0117: ldc.i4 0xc6284d42 IL_011c: beq IL_01f1 IL_0121: ldloc.1 IL_0122: ldc.i4 0xd1761402 IL_0127: beq IL_01c7 IL_012c: ldloc.1 IL_012d: ldc.i4 0xd59864f4 IL_0132: beq IL_026f IL_0137: br IL_0453 IL_013c: ldloc.1 IL_013d: ldc.i4 0xeb323c73 IL_0142: bgt.un.s IL_016a IL_0144: ldloc.1 IL_0145: ldc.i4 0xdca4b248 IL_014a: beq IL_0245 IL_014f: ldloc.1 IL_0150: ldc.i4 0xe926f470 IL_0155: beq IL_036b IL_015a: ldloc.1 IL_015b: ldc.i4 0xeb323c73 IL_0160: beq IL_02d8 IL_0165: br IL_0453 IL_016a: ldloc.1 IL_016b: ldc.i4 0xf1ea0ad5 IL_0170: beq IL_0341 IL_0175: ldloc.1 IL_0176: ldc.i4 0xfa67b44d IL_017b: beq.s IL_019d IL_017d: ldloc.1 IL_017e: ldc.i4 0xfea21584 IL_0183: bne.un IL_0453 IL_0188: ldarg.0 IL_0189: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"" IL_018e: call ""bool string.op_Equality(string, string)"" IL_0193: brtrue IL_0380 IL_0198: br IL_0453 IL_019d: ldarg.0 IL_019e: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"" IL_01a3: call ""bool string.op_Equality(string, string)"" IL_01a8: brtrue IL_038b IL_01ad: br IL_0453 IL_01b2: ldarg.0 IL_01b3: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"" IL_01b8: call ""bool string.op_Equality(string, string)"" IL_01bd: brtrue IL_0396 IL_01c2: br IL_0453 IL_01c7: ldarg.0 IL_01c8: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"" IL_01cd: call ""bool string.op_Equality(string, string)"" IL_01d2: brtrue IL_03a1 IL_01d7: br IL_0453 IL_01dc: ldarg.0 IL_01dd: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"" IL_01e2: call ""bool string.op_Equality(string, string)"" IL_01e7: brtrue IL_03ac IL_01ec: br IL_0453 IL_01f1: ldarg.0 IL_01f2: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"" IL_01f7: call ""bool string.op_Equality(string, string)"" IL_01fc: brtrue IL_03b7 IL_0201: br IL_0453 IL_0206: ldarg.0 IL_0207: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"" IL_020c: call ""bool string.op_Equality(string, string)"" IL_0211: brtrue IL_03c2 IL_0216: br IL_0453 IL_021b: ldarg.0 IL_021c: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"" IL_0221: call ""bool string.op_Equality(string, string)"" IL_0226: brtrue IL_03cd IL_022b: br IL_0453 IL_0230: ldarg.0 IL_0231: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"" IL_0236: call ""bool string.op_Equality(string, string)"" IL_023b: brtrue IL_03d5 IL_0240: br IL_0453 IL_0245: ldarg.0 IL_0246: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"" IL_024b: call ""bool string.op_Equality(string, string)"" IL_0250: brtrue IL_03dd IL_0255: br IL_0453 IL_025a: ldarg.0 IL_025b: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"" IL_0260: call ""bool string.op_Equality(string, string)"" IL_0265: brtrue IL_03e5 IL_026a: br IL_0453 IL_026f: ldarg.0 IL_0270: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"" IL_0275: call ""bool string.op_Equality(string, string)"" IL_027a: brtrue IL_03ed IL_027f: br IL_0453 IL_0284: ldarg.0 IL_0285: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"" IL_028a: call ""bool string.op_Equality(string, string)"" IL_028f: brtrue IL_03f5 IL_0294: br IL_0453 IL_0299: ldarg.0 IL_029a: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"" IL_029f: call ""bool string.op_Equality(string, string)"" IL_02a4: brtrue IL_03fd IL_02a9: br IL_0453 IL_02ae: ldarg.0 IL_02af: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"" IL_02b4: call ""bool string.op_Equality(string, string)"" IL_02b9: brtrue IL_0405 IL_02be: br IL_0453 IL_02c3: ldarg.0 IL_02c4: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"" IL_02c9: call ""bool string.op_Equality(string, string)"" IL_02ce: brtrue IL_040d IL_02d3: br IL_0453 IL_02d8: ldarg.0 IL_02d9: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"" IL_02de: call ""bool string.op_Equality(string, string)"" IL_02e3: brtrue IL_0415 IL_02e8: br IL_0453 IL_02ed: ldarg.0 IL_02ee: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"" IL_02f3: call ""bool string.op_Equality(string, string)"" IL_02f8: brtrue IL_041d IL_02fd: br IL_0453 IL_0302: ldarg.0 IL_0303: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"" IL_0308: call ""bool string.op_Equality(string, string)"" IL_030d: brtrue IL_0425 IL_0312: br IL_0453 IL_0317: ldarg.0 IL_0318: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"" IL_031d: call ""bool string.op_Equality(string, string)"" IL_0322: brtrue IL_042d IL_0327: br IL_0453 IL_032c: ldarg.0 IL_032d: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"" IL_0332: call ""bool string.op_Equality(string, string)"" IL_0337: brtrue IL_0435 IL_033c: br IL_0453 IL_0341: ldarg.0 IL_0342: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"" IL_0347: call ""bool string.op_Equality(string, string)"" IL_034c: brtrue IL_043d IL_0351: br IL_0453 IL_0356: ldarg.0 IL_0357: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"" IL_035c: call ""bool string.op_Equality(string, string)"" IL_0361: brtrue IL_0445 IL_0366: br IL_0453 IL_036b: ldarg.0 IL_036c: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"" IL_0371: call ""bool string.op_Equality(string, string)"" IL_0376: brtrue IL_044d IL_037b: br IL_0453 IL_0380: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"" IL_0385: stloc.0 IL_0386: br IL_0453 IL_038b: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"" IL_0390: stloc.0 IL_0391: br IL_0453 IL_0396: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"" IL_039b: stloc.0 IL_039c: br IL_0453 IL_03a1: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"" IL_03a6: stloc.0 IL_03a7: br IL_0453 IL_03ac: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"" IL_03b1: stloc.0 IL_03b2: br IL_0453 IL_03b7: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"" IL_03bc: stloc.0 IL_03bd: br IL_0453 IL_03c2: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"" IL_03c7: stloc.0 IL_03c8: br IL_0453 IL_03cd: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"" IL_03d2: stloc.0 IL_03d3: br.s IL_0453 IL_03d5: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"" IL_03da: stloc.0 IL_03db: br.s IL_0453 IL_03dd: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"" IL_03e2: stloc.0 IL_03e3: br.s IL_0453 IL_03e5: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"" IL_03ea: stloc.0 IL_03eb: br.s IL_0453 IL_03ed: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"" IL_03f2: stloc.0 IL_03f3: br.s IL_0453 IL_03f5: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"" IL_03fa: stloc.0 IL_03fb: br.s IL_0453 IL_03fd: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"" IL_0402: stloc.0 IL_0403: br.s IL_0453 IL_0405: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"" IL_040a: stloc.0 IL_040b: br.s IL_0453 IL_040d: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"" IL_0412: stloc.0 IL_0413: br.s IL_0453 IL_0415: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"" IL_041a: stloc.0 IL_041b: br.s IL_0453 IL_041d: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"" IL_0422: stloc.0 IL_0423: br.s IL_0453 IL_0425: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"" IL_042a: stloc.0 IL_042b: br.s IL_0453 IL_042d: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"" IL_0432: stloc.0 IL_0433: br.s IL_0453 IL_0435: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"" IL_043a: stloc.0 IL_043b: br.s IL_0453 IL_043d: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"" IL_0442: stloc.0 IL_0443: br.s IL_0453 IL_0445: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"" IL_044a: stloc.0 IL_044b: br.s IL_0453 IL_044d: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"" IL_0452: stloc.0 IL_0453: ldloc.0 IL_0454: ldarg.0 IL_0455: call ""bool string.op_Equality(string, string)"" IL_045a: ret }" ); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); } [WorkItem(544322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544322")] [Fact] public void StringSwitch_HashTableSwitch_03() { var text = @" using System; class Goo { public static void Main() { Console.WriteLine(M(""blah"")); } static int M(string s) { byte[] bytes = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}; switch (s) { case ""blah"": return 1; case ""help"": return 2; case ""ooof"": return 3; case ""walk"": return 4; case ""bark"": return 5; case ""xblah"": return 1; case ""xhelp"": return 2; case ""xooof"": return 3; case ""xwalk"": return 4; case ""xbark"": return 5; case ""rblah"": return 1; case ""rhelp"": return 2; case ""rooof"": return 3; case ""rwalk"": return 4; case ""rbark"": return 5; } return bytes.Length; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "1"); // Verify string hash synthesized method for hash table switch VerifySynthesizedStringHashMethod(compVerifier, expected: true); } private static void VerifySynthesizedStringHashMethod(CompilationVerifier compVerifier, bool expected) { compVerifier.VerifyMemberInIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, expected); if (expected) { compVerifier.VerifyIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, @" { // Code size 44 (0x2c) .maxstack 2 .locals init (uint V_0, int V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_002a IL_0003: ldc.i4 0x811c9dc5 IL_0008: stloc.0 IL_0009: ldc.i4.0 IL_000a: stloc.1 IL_000b: br.s IL_0021 IL_000d: ldarg.0 IL_000e: ldloc.1 IL_000f: callvirt ""char string.this[int].get"" IL_0014: ldloc.0 IL_0015: xor IL_0016: ldc.i4 0x1000193 IL_001b: mul IL_001c: stloc.0 IL_001d: ldloc.1 IL_001e: ldc.i4.1 IL_001f: add IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldarg.0 IL_0023: callvirt ""int string.Length.get"" IL_0028: blt.s IL_000d IL_002a: ldloc.0 IL_002b: ret } "); } } #endregion #region "Implicit user defined conversion tests" [WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")] [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_01() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var source = @"using System; public class Test { public static implicit operator int(Test val) { return 1; } public static implicit operator float(Test val2) { return 2.1f; } public static int Main() { Test t = new Test(); switch (t) { case 1: Console.WriteLine(0); return 0; default: Console.WriteLine(1); return 1; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"0"); } [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_02() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" class X {} class Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator X (Conv C2) { return new X(); } public static int Main() { Conv C = new Conv(); switch(C) { case 1: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_03() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" enum X { F = 0 } class Conv { // only valid operator public static implicit operator int (Conv C) { return 1; } // bool type is not valid public static implicit operator bool (Conv C2) { return false; } // enum type is not valid public static implicit operator X (Conv C3) { return X.F; } public static int Main() { Conv C = new Conv(); switch(C) { case 1: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_04() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C2) { return null; } public static int Main() { Conv? D = new Conv(); switch(D) { case 1: System.Console.WriteLine(""Fail""); return 1; case null: System.Console.WriteLine(""Pass""); return 0; default: System.Console.WriteLine(""Fail""); return 1; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_06() { // Exactly ONE user-defined implicit conversion (6.4) must exist from the type of // the switch expression to one of the following possible governing types: sbyte, byte, short, // ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if // more than one such implicit conversion exists, a compile-time error occurs. var text = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C) { return null; } public static int Main() { Conv? C = new Conv(); switch(C) { case null: System.Console.WriteLine(""Pass""); return 0; case 1: System.Console.WriteLine(""Fail""); return 0; default: System.Console.WriteLine(""Fail""); return 0; } } } "; CompileAndVerify(text, expectedOutput: "Pass"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_3() { var text = @"using System; struct A { public static implicit operator int?(A? a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A a) { Console.WriteLine(""1""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "0"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_4() { var text = @"using System; struct A { public static implicit operator int?(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A? a) { Console.WriteLine(""1""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_1() { var text = @"using System; struct A { public static implicit operator int(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int(A? a) { Console.WriteLine(""1""); return 0; } public static implicit operator int?(A a) { Console.WriteLine(""2""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } [WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")] [Fact()] public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_3() { var text = @"using System; struct A { public static implicit operator int?(A a) { Console.WriteLine(""0""); return 0; } public static implicit operator int?(A? a) { Console.WriteLine(""1""); return 0; } public static implicit operator int(A a) { Console.WriteLine(""2""); return 0; } class B { static void Main() { A? aNullable = new A(); switch(aNullable) { default: break; } } } } "; CompileAndVerify(text, expectedOutput: "1"); } #endregion [WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")] [Fact()] public void MissingCharsProperty() { var text = @" using System; class Program { static string d = null; static void Main() { string s = ""hello""; switch (s) { case ""Hi"": d = "" Hi ""; break; case ""Bye"": d = "" Bye ""; break; case ""qwe"": d = "" qwe ""; break; case ""ert"": d = "" ert ""; break; case ""asd"": d = "" asd ""; break; case ""hello"": d = "" hello ""; break; case ""qrs"": d = "" qrs ""; break; case ""tuv"": d = "" tuv ""; break; case ""wxy"": d = "" wxy ""; break; } } } "; var comp = CreateEmptyCompilation( source: new[] { Parse(text) }, references: new[] { AacorlibRef }); var verifier = CompileAndVerify(comp, verify: Verification.Fails); verifier.VerifyIL("Program.Main", @" { // Code size 223 (0xdf) .maxstack 2 .locals init (string V_0) //s IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""Hi"" IL_000c: call ""bool string.op_Equality(string, string)"" IL_0011: brtrue.s IL_007c IL_0013: ldloc.0 IL_0014: ldstr ""Bye"" IL_0019: call ""bool string.op_Equality(string, string)"" IL_001e: brtrue.s IL_0087 IL_0020: ldloc.0 IL_0021: ldstr ""qwe"" IL_0026: call ""bool string.op_Equality(string, string)"" IL_002b: brtrue.s IL_0092 IL_002d: ldloc.0 IL_002e: ldstr ""ert"" IL_0033: call ""bool string.op_Equality(string, string)"" IL_0038: brtrue.s IL_009d IL_003a: ldloc.0 IL_003b: ldstr ""asd"" IL_0040: call ""bool string.op_Equality(string, string)"" IL_0045: brtrue.s IL_00a8 IL_0047: ldloc.0 IL_0048: ldstr ""hello"" IL_004d: call ""bool string.op_Equality(string, string)"" IL_0052: brtrue.s IL_00b3 IL_0054: ldloc.0 IL_0055: ldstr ""qrs"" IL_005a: call ""bool string.op_Equality(string, string)"" IL_005f: brtrue.s IL_00be IL_0061: ldloc.0 IL_0062: ldstr ""tuv"" IL_0067: call ""bool string.op_Equality(string, string)"" IL_006c: brtrue.s IL_00c9 IL_006e: ldloc.0 IL_006f: ldstr ""wxy"" IL_0074: call ""bool string.op_Equality(string, string)"" IL_0079: brtrue.s IL_00d4 IL_007b: ret IL_007c: ldstr "" Hi "" IL_0081: stsfld ""string Program.d"" IL_0086: ret IL_0087: ldstr "" Bye "" IL_008c: stsfld ""string Program.d"" IL_0091: ret IL_0092: ldstr "" qwe "" IL_0097: stsfld ""string Program.d"" IL_009c: ret IL_009d: ldstr "" ert "" IL_00a2: stsfld ""string Program.d"" IL_00a7: ret IL_00a8: ldstr "" asd "" IL_00ad: stsfld ""string Program.d"" IL_00b2: ret IL_00b3: ldstr "" hello "" IL_00b8: stsfld ""string Program.d"" IL_00bd: ret IL_00be: ldstr "" qrs "" IL_00c3: stsfld ""string Program.d"" IL_00c8: ret IL_00c9: ldstr "" tuv "" IL_00ce: stsfld ""string Program.d"" IL_00d3: ret IL_00d4: ldstr "" wxy "" IL_00d9: stsfld ""string Program.d"" IL_00de: ret }"); } [WorkItem(642186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642186")] [Fact()] public void IsWarningSwitchEmit() { var text = @" using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication24 { class Program { static void Main(string[] args) { TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); TimeIt(); } private static void TimeIt() { // var sw = System.Diagnostics.Stopwatch.StartNew(); // // for (int i = 0; i < 100000000; i++) // { // IsWarning((ErrorCode)(i % 10002)); // } // // sw.Stop(); // System.Console.WriteLine(sw.ElapsedMilliseconds); } public static bool IsWarning(ErrorCode code) { switch (code) { case ErrorCode.WRN_InvalidMainSig: case ErrorCode.WRN_UnreferencedEvent: case ErrorCode.WRN_LowercaseEllSuffix: case ErrorCode.WRN_DuplicateUsing: case ErrorCode.WRN_NewRequired: case ErrorCode.WRN_NewNotRequired: case ErrorCode.WRN_NewOrOverrideExpected: case ErrorCode.WRN_UnreachableCode: case ErrorCode.WRN_UnreferencedLabel: case ErrorCode.WRN_UnreferencedVar: case ErrorCode.WRN_UnreferencedField: case ErrorCode.WRN_IsAlwaysTrue: case ErrorCode.WRN_IsAlwaysFalse: case ErrorCode.WRN_ByRefNonAgileField: case ErrorCode.WRN_OldWarning_UnsafeProp: case ErrorCode.WRN_UnreferencedVarAssg: case ErrorCode.WRN_NegativeArrayIndex: case ErrorCode.WRN_BadRefCompareLeft: case ErrorCode.WRN_BadRefCompareRight: case ErrorCode.WRN_PatternIsAmbiguous: case ErrorCode.WRN_PatternStaticOrInaccessible: case ErrorCode.WRN_PatternBadSignature: case ErrorCode.WRN_SequentialOnPartialClass: case ErrorCode.WRN_MainCantBeGeneric: case ErrorCode.WRN_UnreferencedFieldAssg: case ErrorCode.WRN_AmbiguousXMLReference: case ErrorCode.WRN_VolatileByRef: case ErrorCode.WRN_IncrSwitchObsolete: case ErrorCode.WRN_UnreachableExpr: case ErrorCode.WRN_SameFullNameThisNsAgg: case ErrorCode.WRN_SameFullNameThisAggAgg: case ErrorCode.WRN_SameFullNameThisAggNs: case ErrorCode.WRN_GlobalAliasDefn: case ErrorCode.WRN_UnexpectedPredefTypeLoc: case ErrorCode.WRN_AlwaysNull: case ErrorCode.WRN_CmpAlwaysFalse: case ErrorCode.WRN_FinalizeMethod: case ErrorCode.WRN_AmbigLookupMeth: case ErrorCode.WRN_GotoCaseShouldConvert: case ErrorCode.WRN_NubExprIsConstBool: case ErrorCode.WRN_ExplicitImplCollision: case ErrorCode.WRN_FeatureDeprecated: case ErrorCode.WRN_DeprecatedSymbol: case ErrorCode.WRN_DeprecatedSymbolStr: case ErrorCode.WRN_ExternMethodNoImplementation: case ErrorCode.WRN_ProtectedInSealed: case ErrorCode.WRN_PossibleMistakenNullStatement: case ErrorCode.WRN_UnassignedInternalField: case ErrorCode.WRN_VacuousIntegralComp: case ErrorCode.WRN_AttributeLocationOnBadDeclaration: case ErrorCode.WRN_InvalidAttributeLocation: case ErrorCode.WRN_EqualsWithoutGetHashCode: case ErrorCode.WRN_EqualityOpWithoutEquals: case ErrorCode.WRN_EqualityOpWithoutGetHashCode: case ErrorCode.WRN_IncorrectBooleanAssg: case ErrorCode.WRN_NonObsoleteOverridingObsolete: case ErrorCode.WRN_BitwiseOrSignExtend: case ErrorCode.WRN_OldWarning_ProtectedInternal: case ErrorCode.WRN_OldWarning_AccessibleReadonly: case ErrorCode.WRN_CoClassWithoutComImport: case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter: case ErrorCode.WRN_AssignmentToLockOrDispose: case ErrorCode.WRN_ObsoleteOverridingNonObsolete: case ErrorCode.WRN_DebugFullNameTooLong: case ErrorCode.WRN_ExternCtorNoImplementation: case ErrorCode.WRN_WarningDirective: case ErrorCode.WRN_UnreachableGeneralCatch: case ErrorCode.WRN_UninitializedField: case ErrorCode.WRN_DeprecatedCollectionInitAddStr: case ErrorCode.WRN_DeprecatedCollectionInitAdd: case ErrorCode.WRN_DefaultValueForUnconsumedLocation: case ErrorCode.WRN_FeatureDeprecated2: case ErrorCode.WRN_FeatureDeprecated3: case ErrorCode.WRN_FeatureDeprecated4: case ErrorCode.WRN_FeatureDeprecated5: case ErrorCode.WRN_OldWarning_FeatureDefaultDeprecated: case ErrorCode.WRN_EmptySwitch: case ErrorCode.WRN_XMLParseError: case ErrorCode.WRN_DuplicateParamTag: case ErrorCode.WRN_UnmatchedParamTag: case ErrorCode.WRN_MissingParamTag: case ErrorCode.WRN_BadXMLRef: case ErrorCode.WRN_BadXMLRefParamType: case ErrorCode.WRN_BadXMLRefReturnType: case ErrorCode.WRN_BadXMLRefSyntax: case ErrorCode.WRN_UnprocessedXMLComment: case ErrorCode.WRN_FailedInclude: case ErrorCode.WRN_InvalidInclude: case ErrorCode.WRN_MissingXMLComment: case ErrorCode.WRN_XMLParseIncludeError: case ErrorCode.WRN_OldWarning_MultipleTypeDefs: case ErrorCode.WRN_OldWarning_DocFileGenAndIncr: case ErrorCode.WRN_XMLParserNotFound: case ErrorCode.WRN_ALinkWarn: case ErrorCode.WRN_DeleteAutoResFailed: case ErrorCode.WRN_CmdOptionConflictsSource: case ErrorCode.WRN_IllegalPragma: case ErrorCode.WRN_IllegalPPWarning: case ErrorCode.WRN_BadRestoreNumber: case ErrorCode.WRN_NonECMAFeature: case ErrorCode.WRN_ErrorOverride: case ErrorCode.WRN_OldWarning_ReservedIdentifier: case ErrorCode.WRN_InvalidSearchPathDir: case ErrorCode.WRN_MissingTypeNested: case ErrorCode.WRN_MissingTypeInSource: case ErrorCode.WRN_MissingTypeInAssembly: case ErrorCode.WRN_MultiplePredefTypes: case ErrorCode.WRN_TooManyLinesForDebugger: case ErrorCode.WRN_CallOnNonAgileField: case ErrorCode.WRN_BadWarningNumber: case ErrorCode.WRN_InvalidNumber: case ErrorCode.WRN_FileNameTooLong: case ErrorCode.WRN_IllegalPPChecksum: case ErrorCode.WRN_EndOfPPLineExpected: case ErrorCode.WRN_ConflictingChecksum: case ErrorCode.WRN_AssumedMatchThis: case ErrorCode.WRN_UseSwitchInsteadOfAttribute: case ErrorCode.WRN_InvalidAssemblyName: case ErrorCode.WRN_UnifyReferenceMajMin: case ErrorCode.WRN_UnifyReferenceBldRev: case ErrorCode.WRN_DelegateNewMethBind: case ErrorCode.WRN_EmptyFileName: case ErrorCode.WRN_DuplicateTypeParamTag: case ErrorCode.WRN_UnmatchedTypeParamTag: case ErrorCode.WRN_MissingTypeParamTag: case ErrorCode.WRN_AssignmentToSelf: case ErrorCode.WRN_ComparisonToSelf: case ErrorCode.WRN_DotOnDefault: case ErrorCode.WRN_BadXMLRefTypeVar: case ErrorCode.WRN_UnmatchedParamRefTag: case ErrorCode.WRN_UnmatchedTypeParamRefTag: case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA: case ErrorCode.WRN_TypeNotFoundForNoPIAWarning: case ErrorCode.WRN_CantHaveManifestForModule: case ErrorCode.WRN_MultipleRuntimeImplementationMatches: case ErrorCode.WRN_MultipleRuntimeOverrideMatches: case ErrorCode.WRN_DynamicDispatchToConditionalMethod: case ErrorCode.WRN_IsDynamicIsConfusing: case ErrorCode.WRN_AsyncLacksAwaits: case ErrorCode.WRN_FileAlreadyIncluded: case ErrorCode.WRN_NoSources: case ErrorCode.WRN_UseNewSwitch: case ErrorCode.WRN_NoConfigNotOnCommandLine: case ErrorCode.WRN_DefineIdentifierRequired: case ErrorCode.WRN_BadUILang: case ErrorCode.WRN_CLS_NoVarArgs: case ErrorCode.WRN_CLS_BadArgType: case ErrorCode.WRN_CLS_BadReturnType: case ErrorCode.WRN_CLS_BadFieldPropType: case ErrorCode.WRN_CLS_BadUnicode: case ErrorCode.WRN_CLS_BadIdentifierCase: case ErrorCode.WRN_CLS_OverloadRefOut: case ErrorCode.WRN_CLS_OverloadUnnamed: case ErrorCode.WRN_CLS_BadIdentifier: case ErrorCode.WRN_CLS_BadBase: case ErrorCode.WRN_CLS_BadInterfaceMember: case ErrorCode.WRN_CLS_NoAbstractMembers: case ErrorCode.WRN_CLS_NotOnModules: case ErrorCode.WRN_CLS_ModuleMissingCLS: case ErrorCode.WRN_CLS_AssemblyNotCLS: case ErrorCode.WRN_CLS_BadAttributeType: case ErrorCode.WRN_CLS_ArrayArgumentToAttribute: case ErrorCode.WRN_CLS_NotOnModules2: case ErrorCode.WRN_CLS_IllegalTrueInFalse: case ErrorCode.WRN_CLS_MeaninglessOnPrivateType: case ErrorCode.WRN_CLS_AssemblyNotCLS2: case ErrorCode.WRN_CLS_MeaninglessOnParam: case ErrorCode.WRN_CLS_MeaninglessOnReturn: case ErrorCode.WRN_CLS_BadTypeVar: case ErrorCode.WRN_CLS_VolatileField: case ErrorCode.WRN_CLS_BadInterface: case ErrorCode.WRN_UnobservedAwaitableExpression: case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation: case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation: case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation: case ErrorCode.WRN_UnknownOption: case ErrorCode.WRN_MetadataNameTooLong: case ErrorCode.WRN_MainIgnored: case ErrorCode.WRN_DelaySignButNoKey: case ErrorCode.WRN_InvalidVersionFormat: case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName: case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName: case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath: case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden: case ErrorCode.WRN_UnimplementedCommandLineSwitch: case ErrorCode.WRN_RefCultureMismatch: case ErrorCode.WRN_ConflictingMachineAssembly: case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope1: case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope2: case ErrorCode.WRN_CA2202_DoNotDisposeObjectsMultipleTimes: return true; default: return false; } } internal enum ErrorCode { Void = InternalErrorCode.Void, Unknown = InternalErrorCode.Unknown, FTL_InternalError = 1, //FTL_FailedToLoadResource = 2, //FTL_NoMemory = 3, //ERR_WarningAsError = 4, //ERR_MissingOptionArg = 5, ERR_NoMetadataFile = 6, //FTL_ComPlusInit = 7, FTL_MetadataImportFailure = 8, FTL_MetadataCantOpenFile = 9, //ERR_FatalError = 10, //ERR_CantImportBase = 11, ERR_NoTypeDef = 12, FTL_MetadataEmitFailure = 13, //FTL_RequiredFileNotFound = 14, ERR_ClassNameTooLong = 15, ERR_OutputWriteFailed = 16, ERR_MultipleEntryPoints = 17, //ERR_UnimplementedOp = 18, ERR_BadBinaryOps = 19, ERR_IntDivByZero = 20, ERR_BadIndexLHS = 21, ERR_BadIndexCount = 22, ERR_BadUnaryOp = 23, //ERR_NoStdLib = 25, not used in Roslyn ERR_ThisInStaticMeth = 26, ERR_ThisInBadContext = 27, WRN_InvalidMainSig = 28, ERR_NoImplicitConv = 29, ERR_NoExplicitConv = 30, ERR_ConstOutOfRange = 31, ERR_AmbigBinaryOps = 34, ERR_AmbigUnaryOp = 35, ERR_InAttrOnOutParam = 36, ERR_ValueCantBeNull = 37, //ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired ""An object reference is required for the non-static..."" ERR_NoExplicitBuiltinConv = 39, //FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. FTL_DebugEmitFailure = 41, //FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info. //FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. ERR_BadVisReturnType = 50, ERR_BadVisParamType = 51, ERR_BadVisFieldType = 52, ERR_BadVisPropertyType = 53, ERR_BadVisIndexerReturn = 54, ERR_BadVisIndexerParam = 55, ERR_BadVisOpReturn = 56, ERR_BadVisOpParam = 57, ERR_BadVisDelegateReturn = 58, ERR_BadVisDelegateParam = 59, ERR_BadVisBaseClass = 60, ERR_BadVisBaseInterface = 61, ERR_EventNeedsBothAccessors = 65, ERR_EventNotDelegate = 66, WRN_UnreferencedEvent = 67, ERR_InterfaceEventInitializer = 68, ERR_EventPropertyInInterface = 69, ERR_BadEventUsage = 70, ERR_ExplicitEventFieldImpl = 71, ERR_CantOverrideNonEvent = 72, ERR_AddRemoveMustHaveBody = 73, ERR_AbstractEventInitializer = 74, ERR_PossibleBadNegCast = 75, ERR_ReservedEnumerator = 76, ERR_AsMustHaveReferenceType = 77, WRN_LowercaseEllSuffix = 78, ERR_BadEventUsageNoField = 79, ERR_ConstraintOnlyAllowedOnGenericDecl = 80, ERR_TypeParamMustBeIdentifier = 81, ERR_MemberReserved = 82, ERR_DuplicateParamName = 100, ERR_DuplicateNameInNS = 101, ERR_DuplicateNameInClass = 102, ERR_NameNotInContext = 103, ERR_AmbigContext = 104, WRN_DuplicateUsing = 105, ERR_BadMemberFlag = 106, ERR_BadMemberProtection = 107, WRN_NewRequired = 108, WRN_NewNotRequired = 109, ERR_CircConstValue = 110, ERR_MemberAlreadyExists = 111, ERR_StaticNotVirtual = 112, ERR_OverrideNotNew = 113, WRN_NewOrOverrideExpected = 114, ERR_OverrideNotExpected = 115, ERR_NamespaceUnexpected = 116, ERR_NoSuchMember = 117, ERR_BadSKknown = 118, ERR_BadSKunknown = 119, ERR_ObjectRequired = 120, ERR_AmbigCall = 121, ERR_BadAccess = 122, ERR_MethDelegateMismatch = 123, ERR_RetObjectRequired = 126, ERR_RetNoObjectRequired = 127, ERR_LocalDuplicate = 128, ERR_AssgLvalueExpected = 131, ERR_StaticConstParam = 132, ERR_NotConstantExpression = 133, ERR_NotNullConstRefField = 134, ERR_NameIllegallyOverrides = 135, ERR_LocalIllegallyOverrides = 136, ERR_BadUsingNamespace = 138, ERR_NoBreakOrCont = 139, ERR_DuplicateLabel = 140, ERR_NoConstructors = 143, ERR_NoNewAbstract = 144, ERR_ConstValueRequired = 145, ERR_CircularBase = 146, ERR_BadDelegateConstructor = 148, ERR_MethodNameExpected = 149, ERR_ConstantExpected = 150, // ERR_SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler. // However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future // we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used. ERR_SwitchGoverningTypeValueExpected = 151, ERR_DuplicateCaseLabel = 152, ERR_InvalidGotoCase = 153, ERR_PropertyLacksGet = 154, ERR_BadExceptionType = 155, ERR_BadEmptyThrow = 156, ERR_BadFinallyLeave = 157, ERR_LabelShadow = 158, ERR_LabelNotFound = 159, ERR_UnreachableCatch = 160, ERR_ReturnExpected = 161, WRN_UnreachableCode = 162, ERR_SwitchFallThrough = 163, WRN_UnreferencedLabel = 164, ERR_UseDefViolation = 165, //ERR_NoInvoke = 167, WRN_UnreferencedVar = 168, WRN_UnreferencedField = 169, ERR_UseDefViolationField = 170, ERR_UnassignedThis = 171, ERR_AmbigQM = 172, ERR_InvalidQM = 173, ERR_NoBaseClass = 174, ERR_BaseIllegal = 175, ERR_ObjectProhibited = 176, ERR_ParamUnassigned = 177, ERR_InvalidArray = 178, ERR_ExternHasBody = 179, ERR_AbstractAndExtern = 180, ERR_BadAttributeParamType = 181, ERR_BadAttributeArgument = 182, WRN_IsAlwaysTrue = 183, WRN_IsAlwaysFalse = 184, ERR_LockNeedsReference = 185, ERR_NullNotValid = 186, ERR_UseDefViolationThis = 188, ERR_ArgsInvalid = 190, ERR_AssgReadonly = 191, ERR_RefReadonly = 192, ERR_PtrExpected = 193, ERR_PtrIndexSingle = 196, WRN_ByRefNonAgileField = 197, ERR_AssgReadonlyStatic = 198, ERR_RefReadonlyStatic = 199, ERR_AssgReadonlyProp = 200, ERR_IllegalStatement = 201, ERR_BadGetEnumerator = 202, ERR_TooManyLocals = 204, ERR_AbstractBaseCall = 205, ERR_RefProperty = 206, WRN_OldWarning_UnsafeProp = 207, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:207"" is specified on the command line. ERR_ManagedAddr = 208, ERR_BadFixedInitType = 209, ERR_FixedMustInit = 210, ERR_InvalidAddrOp = 211, ERR_FixedNeeded = 212, ERR_FixedNotNeeded = 213, ERR_UnsafeNeeded = 214, ERR_OpTFRetType = 215, ERR_OperatorNeedsMatch = 216, ERR_BadBoolOp = 217, ERR_MustHaveOpTF = 218, WRN_UnreferencedVarAssg = 219, ERR_CheckedOverflow = 220, ERR_ConstOutOfRangeChecked = 221, ERR_BadVarargs = 224, ERR_ParamsMustBeArray = 225, ERR_IllegalArglist = 226, ERR_IllegalUnsafe = 227, //ERR_NoAccessibleMember = 228, ERR_AmbigMember = 229, ERR_BadForeachDecl = 230, ERR_ParamsLast = 231, ERR_SizeofUnsafe = 233, ERR_DottedTypeNameNotFoundInNS = 234, ERR_FieldInitRefNonstatic = 236, ERR_SealedNonOverride = 238, ERR_CantOverrideSealed = 239, //ERR_NoDefaultArgs = 241, ERR_VoidError = 242, ERR_ConditionalOnOverride = 243, ERR_PointerInAsOrIs = 244, ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated ERR_SingleTypeNameNotFound = 246, ERR_NegativeStackAllocSize = 247, ERR_NegativeArraySize = 248, ERR_OverrideFinalizeDeprecated = 249, ERR_CallingBaseFinalizeDeprecated = 250, WRN_NegativeArrayIndex = 251, WRN_BadRefCompareLeft = 252, WRN_BadRefCompareRight = 253, ERR_BadCastInFixed = 254, ERR_StackallocInCatchFinally = 255, ERR_VarargsLast = 257, ERR_MissingPartial = 260, ERR_PartialTypeKindConflict = 261, ERR_PartialModifierConflict = 262, ERR_PartialMultipleBases = 263, ERR_PartialWrongTypeParams = 264, ERR_PartialWrongConstraints = 265, ERR_NoImplicitConvCast = 266, ERR_PartialMisplaced = 267, ERR_ImportedCircularBase = 268, ERR_UseDefViolationOut = 269, ERR_ArraySizeInDeclaration = 270, ERR_InaccessibleGetter = 271, ERR_InaccessibleSetter = 272, ERR_InvalidPropertyAccessMod = 273, ERR_DuplicatePropertyAccessMods = 274, ERR_PropertyAccessModInInterface = 275, ERR_AccessModMissingAccessor = 276, ERR_UnimplementedInterfaceAccessor = 277, WRN_PatternIsAmbiguous = 278, WRN_PatternStaticOrInaccessible = 279, WRN_PatternBadSignature = 280, ERR_FriendRefNotEqualToThis = 281, WRN_SequentialOnPartialClass = 282, ERR_BadConstType = 283, ERR_NoNewTyvar = 304, ERR_BadArity = 305, ERR_BadTypeArgument = 306, ERR_TypeArgsNotAllowed = 307, ERR_HasNoTypeVars = 308, ERR_NewConstraintNotSatisfied = 310, ERR_GenericConstraintNotSatisfiedRefType = 311, ERR_GenericConstraintNotSatisfiedNullableEnum = 312, ERR_GenericConstraintNotSatisfiedNullableInterface = 313, ERR_GenericConstraintNotSatisfiedTyVar = 314, ERR_GenericConstraintNotSatisfiedValType = 315, ERR_DuplicateGeneratedName = 316, ERR_GlobalSingleTypeNameNotFound = 400, ERR_NewBoundMustBeLast = 401, WRN_MainCantBeGeneric = 402, ERR_TypeVarCantBeNull = 403, ERR_AttributeCantBeGeneric = 404, ERR_DuplicateBound = 405, ERR_ClassBoundNotFirst = 406, ERR_BadRetType = 407, ERR_DuplicateConstraintClause = 409, //ERR_WrongSignature = 410, unused in Roslyn ERR_CantInferMethTypeArgs = 411, ERR_LocalSameNameAsTypeParam = 412, ERR_AsWithTypeVar = 413, WRN_UnreferencedFieldAssg = 414, ERR_BadIndexerNameAttr = 415, ERR_AttrArgWithTypeVars = 416, ERR_NewTyvarWithArgs = 417, ERR_AbstractSealedStatic = 418, WRN_AmbiguousXMLReference = 419, WRN_VolatileByRef = 420, WRN_IncrSwitchObsolete = 422, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_ComImportWithImpl = 423, ERR_ComImportWithBase = 424, ERR_ImplBadConstraints = 425, ERR_DottedTypeNameNotFoundInAgg = 426, ERR_MethGrpToNonDel = 428, WRN_UnreachableExpr = 429, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_BadExternAlias = 430, ERR_ColColWithTypeAlias = 431, ERR_AliasNotFound = 432, ERR_SameFullNameAggAgg = 433, ERR_SameFullNameNsAgg = 434, WRN_SameFullNameThisNsAgg = 435, WRN_SameFullNameThisAggAgg = 436, WRN_SameFullNameThisAggNs = 437, ERR_SameFullNameThisAggThisNs = 438, ERR_ExternAfterElements = 439, WRN_GlobalAliasDefn = 440, ERR_SealedStaticClass = 441, ERR_PrivateAbstractAccessor = 442, ERR_ValueExpected = 443, WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line. ERR_UnboxNotLValue = 445, ERR_AnonMethGrpInForEach = 446, //ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error. ERR_BadIncDecRetType = 448, ERR_TypeConstraintsMustBeUniqueAndFirst = 449, ERR_RefValBoundWithClass = 450, ERR_NewBoundWithVal = 451, ERR_RefConstraintNotSatisfied = 452, ERR_ValConstraintNotSatisfied = 453, ERR_CircularConstraint = 454, ERR_BaseConstraintConflict = 455, ERR_ConWithValCon = 456, ERR_AmbigUDConv = 457, WRN_AlwaysNull = 458, ERR_AddrOnReadOnlyLocal = 459, ERR_OverrideWithConstraints = 460, ERR_AmbigOverride = 462, ERR_DecConstError = 463, WRN_CmpAlwaysFalse = 464, WRN_FinalizeMethod = 465, ERR_ExplicitImplParams = 466, WRN_AmbigLookupMeth = 467, ERR_SameFullNameThisAggThisAgg = 468, WRN_GotoCaseShouldConvert = 469, ERR_MethodImplementingAccessor = 470, //ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn WRN_NubExprIsConstBool = 472, WRN_ExplicitImplCollision = 473, ERR_AbstractHasBody = 500, ERR_ConcreteMissingBody = 501, ERR_AbstractAndSealed = 502, ERR_AbstractNotVirtual = 503, ERR_StaticConstant = 504, ERR_CantOverrideNonFunction = 505, ERR_CantOverrideNonVirtual = 506, ERR_CantChangeAccessOnOverride = 507, ERR_CantChangeReturnTypeOnOverride = 508, ERR_CantDeriveFromSealedType = 509, ERR_AbstractInConcreteClass = 513, ERR_StaticConstructorWithExplicitConstructorCall = 514, ERR_StaticConstructorWithAccessModifiers = 515, ERR_RecursiveConstructorCall = 516, ERR_ObjectCallingBaseConstructor = 517, ERR_PredefinedTypeNotFound = 518, //ERR_PredefinedTypeBadType = 520, ERR_StructWithBaseConstructorCall = 522, ERR_StructLayoutCycle = 523, ERR_InterfacesCannotContainTypes = 524, ERR_InterfacesCantContainFields = 525, ERR_InterfacesCantContainConstructors = 526, ERR_NonInterfaceInInterfaceList = 527, ERR_DuplicateInterfaceInBaseList = 528, ERR_CycleInInterfaceInheritance = 529, ERR_InterfaceMemberHasBody = 531, ERR_HidingAbstractMethod = 533, ERR_UnimplementedAbstractMethod = 534, ERR_UnimplementedInterfaceMember = 535, ERR_ObjectCantHaveBases = 537, ERR_ExplicitInterfaceImplementationNotInterface = 538, ERR_InterfaceMemberNotFound = 539, ERR_ClassDoesntImplementInterface = 540, ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541, ERR_MemberNameSameAsType = 542, ERR_EnumeratorOverflow = 543, ERR_CantOverrideNonProperty = 544, ERR_NoGetToOverride = 545, ERR_NoSetToOverride = 546, ERR_PropertyCantHaveVoidType = 547, ERR_PropertyWithNoAccessors = 548, ERR_NewVirtualInSealed = 549, ERR_ExplicitPropertyAddingAccessor = 550, ERR_ExplicitPropertyMissingAccessor = 551, ERR_ConversionWithInterface = 552, ERR_ConversionWithBase = 553, ERR_ConversionWithDerived = 554, ERR_IdentityConversion = 555, ERR_ConversionNotInvolvingContainedType = 556, ERR_DuplicateConversionInClass = 557, ERR_OperatorsMustBeStatic = 558, ERR_BadIncDecSignature = 559, ERR_BadUnaryOperatorSignature = 562, ERR_BadBinaryOperatorSignature = 563, ERR_BadShiftOperatorSignature = 564, ERR_InterfacesCantContainOperators = 567, ERR_StructsCantContainDefaultConstructor = 568, ERR_CantOverrideBogusMethod = 569, ERR_BindToBogus = 570, ERR_CantCallSpecialMethod = 571, ERR_BadTypeReference = 572, ERR_FieldInitializerInStruct = 573, ERR_BadDestructorName = 574, ERR_OnlyClassesCanContainDestructors = 575, ERR_ConflictAliasAndMember = 576, ERR_ConditionalOnSpecialMethod = 577, ERR_ConditionalMustReturnVoid = 578, ERR_DuplicateAttribute = 579, ERR_ConditionalOnInterfaceMethod = 582, //ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused //ERR_ICE_Symbol = 584, //ERR_ICE_Node = 585, //ERR_ICE_File = 586, //ERR_ICE_Stage = 587, //ERR_ICE_Lexer = 588, //ERR_ICE_Parser = 589, ERR_OperatorCantReturnVoid = 590, ERR_InvalidAttributeArgument = 591, ERR_AttributeOnBadSymbolType = 592, ERR_FloatOverflow = 594, ERR_ComImportWithoutUuidAttribute = 596, ERR_InvalidNamedArgument = 599, ERR_DllImportOnInvalidMethod = 601, WRN_FeatureDeprecated = 602, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:602"" is specified on the command line. // ERR_NameAttributeOnOverride = 609, // removed in Roslyn ERR_FieldCantBeRefAny = 610, ERR_ArrayElementCantBeRefAny = 611, WRN_DeprecatedSymbol = 612, ERR_NotAnAttributeClass = 616, ERR_BadNamedAttributeArgument = 617, WRN_DeprecatedSymbolStr = 618, ERR_DeprecatedSymbolStr = 619, ERR_IndexerCantHaveVoidType = 620, ERR_VirtualPrivate = 621, ERR_ArrayInitToNonArrayType = 622, ERR_ArrayInitInBadPlace = 623, ERR_MissingStructOffset = 625, WRN_ExternMethodNoImplementation = 626, WRN_ProtectedInSealed = 628, ERR_InterfaceImplementedByConditional = 629, ERR_IllegalRefParam = 631, ERR_BadArgumentToAttribute = 633, //ERR_MissingComTypeOrMarshaller = 635, ERR_StructOffsetOnBadStruct = 636, ERR_StructOffsetOnBadField = 637, ERR_AttributeUsageOnNonAttributeClass = 641, WRN_PossibleMistakenNullStatement = 642, ERR_DuplicateNamedAttributeArgument = 643, ERR_DeriveFromEnumOrValueType = 644, ERR_DefaultMemberOnIndexedType = 646, //ERR_CustomAttributeError = 647, ERR_BogusType = 648, WRN_UnassignedInternalField = 649, ERR_CStyleArray = 650, WRN_VacuousIntegralComp = 652, ERR_AbstractAttributeClass = 653, ERR_BadNamedAttributeArgumentType = 655, ERR_MissingPredefinedMember = 656, WRN_AttributeLocationOnBadDeclaration = 657, WRN_InvalidAttributeLocation = 658, WRN_EqualsWithoutGetHashCode = 659, WRN_EqualityOpWithoutEquals = 660, WRN_EqualityOpWithoutGetHashCode = 661, ERR_OutAttrOnRefParam = 662, ERR_OverloadRefKind = 663, ERR_LiteralDoubleCast = 664, WRN_IncorrectBooleanAssg = 665, ERR_ProtectedInStruct = 666, //ERR_FeatureDeprecated = 667, ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler ERR_ComImportWithUserCtor = 669, ERR_FieldCantHaveVoidType = 670, WRN_NonObsoleteOverridingObsolete = 672, ERR_SystemVoid = 673, ERR_ExplicitParamArray = 674, WRN_BitwiseOrSignExtend = 675, ERR_VolatileStruct = 677, ERR_VolatileAndReadonly = 678, WRN_OldWarning_ProtectedInternal = 679, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:679"" is specified on the command line. WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:680"" is specified on the command line. ERR_AbstractField = 681, ERR_BogusExplicitImpl = 682, ERR_ExplicitMethodImplAccessor = 683, WRN_CoClassWithoutComImport = 684, ERR_ConditionalWithOutParam = 685, ERR_AccessorImplementingMethod = 686, ERR_AliasQualAsExpression = 687, ERR_DerivingFromATyVar = 689, //FTL_MalformedMetadata = 690, ERR_DuplicateTypeParameter = 692, WRN_TypeParameterSameAsOuterTypeParameter = 693, ERR_TypeVariableSameAsParent = 694, ERR_UnifyingInterfaceInstantiations = 695, ERR_GenericDerivingFromAttribute = 698, ERR_TyVarNotFoundInConstraint = 699, ERR_BadBoundType = 701, ERR_SpecialTypeAsBound = 702, ERR_BadVisBound = 703, ERR_LookupInTypeVariable = 704, ERR_BadConstraintType = 706, ERR_InstanceMemberInStaticClass = 708, ERR_StaticBaseClass = 709, ERR_ConstructorInStaticClass = 710, ERR_DestructorInStaticClass = 711, ERR_InstantiatingStaticClass = 712, ERR_StaticDerivedFromNonObject = 713, ERR_StaticClassInterfaceImpl = 714, ERR_OperatorInStaticClass = 715, ERR_ConvertToStaticClass = 716, ERR_ConstraintIsStaticClass = 717, ERR_GenericArgIsStaticClass = 718, ERR_ArrayOfStaticClass = 719, ERR_IndexerInStaticClass = 720, ERR_ParameterIsStaticClass = 721, ERR_ReturnTypeIsStaticClass = 722, ERR_VarDeclIsStaticClass = 723, ERR_BadEmptyThrowInFinally = 724, //ERR_InvalidDecl = 725, //ERR_InvalidSpecifier = 726, //ERR_InvalidSpecifierUnk = 727, WRN_AssignmentToLockOrDispose = 728, ERR_ForwardedTypeInThisAssembly = 729, ERR_ForwardedTypeIsNested = 730, ERR_CycleInTypeForwarder = 731, //ERR_FwdedGeneric = 733, ERR_AssemblyNameOnNonModule = 734, ERR_InvalidFwdType = 735, ERR_CloseUnimplementedInterfaceMemberStatic = 736, ERR_CloseUnimplementedInterfaceMemberNotPublic = 737, ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738, ERR_DuplicateTypeForwarder = 739, ERR_ExpectedSelectOrGroup = 742, ERR_ExpectedContextualKeywordOn = 743, ERR_ExpectedContextualKeywordEquals = 744, ERR_ExpectedContextualKeywordBy = 745, ERR_InvalidAnonymousTypeMemberDeclarator = 746, ERR_InvalidInitializerElementInitializer = 747, ERR_InconsistentLambdaParameterUsage = 748, ERR_PartialMethodInvalidModifier = 750, ERR_PartialMethodOnlyInPartialClass = 751, ERR_PartialMethodCannotHaveOutParameters = 752, ERR_PartialMethodOnlyMethods = 753, ERR_PartialMethodNotExplicit = 754, ERR_PartialMethodExtensionDifference = 755, ERR_PartialMethodOnlyOneLatent = 756, ERR_PartialMethodOnlyOneActual = 757, ERR_PartialMethodParamsDifference = 758, ERR_PartialMethodMustHaveLatent = 759, ERR_PartialMethodInconsistentConstraints = 761, ERR_PartialMethodToDelegate = 762, ERR_PartialMethodStaticDifference = 763, ERR_PartialMethodUnsafeDifference = 764, ERR_PartialMethodInExpressionTree = 765, ERR_PartialMethodMustReturnVoid = 766, ERR_ExplicitImplCollisionOnRefOut = 767, //ERR_NoEmptyArrayRanges = 800, //ERR_IntegerSpecifierOnOneDimArrays = 801, //ERR_IntegerSpecifierMustBePositive = 802, //ERR_ArrayRangeDimensionsMustMatch = 803, //ERR_ArrayRangeDimensionsWrong = 804, //ERR_IntegerSpecifierValidOnlyOnArrays = 805, //ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806, //ERR_UseAdditionalSquareBrackets = 807, //ERR_DotDotNotAssociative = 808, WRN_ObsoleteOverridingNonObsolete = 809, WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer ERR_ImplicitlyTypedLocalCannotBeFixed = 821, ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst WRN_ExternCtorNoImplementation = 824, ERR_TypeVarNotFound = 825, ERR_ImplicitlyTypedArrayNoBestType = 826, ERR_AnonymousTypePropertyAssignedBadValue = 828, ERR_ExpressionTreeContainsBaseAccess = 831, ERR_ExpressionTreeContainsAssignment = 832, ERR_AnonymousTypeDuplicatePropertyName = 833, ERR_StatementLambdaToExpressionTree = 834, ERR_ExpressionTreeMustHaveDelegate = 835, ERR_AnonymousTypeNotAvailable = 836, ERR_LambdaInIsAs = 837, ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838, ERR_MissingArgument = 839, ERR_AutoPropertiesMustHaveBothAccessors = 840, ERR_VariableUsedBeforeDeclaration = 841, ERR_ExplicitLayoutAndAutoImplementedProperty = 842, ERR_UnassignedThisAutoProperty = 843, ERR_VariableUsedBeforeDeclarationAndHidesField = 844, ERR_ExpressionTreeContainsBadCoalesce = 845, ERR_ArrayInitializerExpected = 846, ERR_ArrayInitializerIncorrectLength = 847, // ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind ERR_ExpressionTreeContainsNamedArgument = 853, ERR_ExpressionTreeContainsOptionalArgument = 854, ERR_ExpressionTreeContainsIndexedProperty = 855, ERR_IndexedPropertyRequiresParams = 856, ERR_IndexedPropertyMustHaveAllOptionalParams = 857, ERR_FusionConfigFileNameTooLong = 858, ERR_IdentifierExpected = 1001, ERR_SemicolonExpected = 1002, ERR_SyntaxError = 1003, ERR_DuplicateModifier = 1004, ERR_DuplicateAccessor = 1007, ERR_IntegralTypeExpected = 1008, ERR_IllegalEscape = 1009, ERR_NewlineInConst = 1010, ERR_EmptyCharConst = 1011, ERR_TooManyCharsInConst = 1012, ERR_InvalidNumber = 1013, ERR_GetOrSetExpected = 1014, ERR_ClassTypeExpected = 1015, ERR_NamedArgumentExpected = 1016, ERR_TooManyCatches = 1017, ERR_ThisOrBaseExpected = 1018, ERR_OvlUnaryOperatorExpected = 1019, ERR_OvlBinaryOperatorExpected = 1020, ERR_IntOverflow = 1021, ERR_EOFExpected = 1022, ERR_BadEmbeddedStmt = 1023, ERR_PPDirectiveExpected = 1024, ERR_EndOfPPLineExpected = 1025, ERR_CloseParenExpected = 1026, ERR_EndifDirectiveExpected = 1027, ERR_UnexpectedDirective = 1028, ERR_ErrorDirective = 1029, WRN_WarningDirective = 1030, ERR_TypeExpected = 1031, ERR_PPDefFollowsToken = 1032, //ERR_TooManyLines = 1033, unused in Roslyn. //ERR_LineTooLong = 1034, unused in Roslyn. ERR_OpenEndedComment = 1035, ERR_OvlOperatorExpected = 1037, ERR_EndRegionDirectiveExpected = 1038, ERR_UnterminatedStringLit = 1039, ERR_BadDirectivePlacement = 1040, ERR_IdentifierExpectedKW = 1041, ERR_SemiOrLBraceExpected = 1043, ERR_MultiTypeInDeclaration = 1044, ERR_AddOrRemoveExpected = 1055, ERR_UnexpectedCharacter = 1056, ERR_ProtectedInStatic = 1057, WRN_UnreachableGeneralCatch = 1058, ERR_IncrementLvalueExpected = 1059, WRN_UninitializedField = 1060, //unused in Roslyn but preserving for the purposes of not breaking users' /nowarn settings ERR_NoSuchMemberOrExtension = 1061, WRN_DeprecatedCollectionInitAddStr = 1062, ERR_DeprecatedCollectionInitAddStr = 1063, WRN_DeprecatedCollectionInitAdd = 1064, ERR_DefaultValueNotAllowed = 1065, WRN_DefaultValueForUnconsumedLocation = 1066, ERR_PartialWrongTypeParamsVariance = 1067, ERR_GlobalSingleTypeNameNotFoundFwd = 1068, ERR_DottedTypeNameNotFoundInNSFwd = 1069, ERR_SingleTypeNameNotFoundFwd = 1070, //ERR_NoSuchMemberOnNoPIAType = 1071, //EE // ERR_EOLExpected = 1099, // EE // ERR_NotSupportedinEE = 1100, // EE ERR_BadThisParam = 1100, ERR_BadRefWithThis = 1101, ERR_BadOutWithThis = 1102, ERR_BadTypeforThis = 1103, ERR_BadParamModThis = 1104, ERR_BadExtensionMeth = 1105, ERR_BadExtensionAgg = 1106, ERR_DupParamMod = 1107, ERR_MultiParamMod = 1108, ERR_ExtensionMethodsDecl = 1109, ERR_ExtensionAttrNotFound = 1110, //ERR_ExtensionTypeParam = 1111, ERR_ExplicitExtension = 1112, ERR_ValueTypeExtDelegate = 1113, // Below five error codes are unused, but we still need to retain them to suppress CS1691 when ""/nowarn:1200,1201,1202,1203,1204"" is specified on the command line. WRN_FeatureDeprecated2 = 1200, WRN_FeatureDeprecated3 = 1201, WRN_FeatureDeprecated4 = 1202, WRN_FeatureDeprecated5 = 1203, WRN_OldWarning_FeatureDefaultDeprecated = 1204, ERR_BadArgCount = 1501, //ERR_BadArgTypes = 1502, ERR_BadArgType = 1503, ERR_NoSourceFile = 1504, ERR_CantRefResource = 1507, ERR_ResourceNotUnique = 1508, ERR_ImportNonAssembly = 1509, ERR_RefLvalueExpected = 1510, ERR_BaseInStaticMeth = 1511, ERR_BaseInBadContext = 1512, ERR_RbraceExpected = 1513, ERR_LbraceExpected = 1514, ERR_InExpected = 1515, ERR_InvalidPreprocExpr = 1517, //ERR_BadTokenInType = 1518, unused in Roslyn ERR_InvalidMemberDecl = 1519, ERR_MemberNeedsType = 1520, ERR_BadBaseType = 1521, WRN_EmptySwitch = 1522, ERR_ExpectedEndTry = 1524, ERR_InvalidExprTerm = 1525, ERR_BadNewExpr = 1526, ERR_NoNamespacePrivate = 1527, ERR_BadVarDecl = 1528, ERR_UsingAfterElements = 1529, //ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this. //ERR_DontUseInvoke = 1533, ERR_BadBinOpArgs = 1534, ERR_BadUnOpArgs = 1535, ERR_NoVoidParameter = 1536, ERR_DuplicateAlias = 1537, ERR_BadProtectedAccess = 1540, //ERR_CantIncludeDirectory = 1541, ERR_AddModuleAssembly = 1542, ERR_BindToBogusProp2 = 1545, ERR_BindToBogusProp1 = 1546, ERR_NoVoidHere = 1547, //ERR_CryptoFailed = 1548, //ERR_CryptoNotFound = 1549, ERR_IndexerNeedsParam = 1551, ERR_BadArraySyntax = 1552, ERR_BadOperatorSyntax = 1553, ERR_BadOperatorSyntax2 = 1554, ERR_MainClassNotFound = 1555, ERR_MainClassNotClass = 1556, ERR_MainClassWrongFile = 1557, ERR_NoMainInClass = 1558, ERR_MainClassIsImport = 1559, //ERR_FileNameTooLong = 1560, ERR_OutputFileNameTooLong = 1561, ERR_OutputNeedsName = 1562, //ERR_OutputNeedsInput = 1563, ERR_CantHaveWin32ResAndManifest = 1564, ERR_CantHaveWin32ResAndIcon = 1565, ERR_CantReadResource = 1566, //ERR_AutoResGen = 1567, //ERR_DocFileGen = 1569, WRN_XMLParseError = 1570, WRN_DuplicateParamTag = 1571, WRN_UnmatchedParamTag = 1572, WRN_MissingParamTag = 1573, WRN_BadXMLRef = 1574, ERR_BadStackAllocExpr = 1575, ERR_InvalidLineNumber = 1576, //ERR_ALinkFailed = 1577, No alink usage in Roslyn ERR_MissingPPFile = 1578, ERR_ForEachMissingMember = 1579, WRN_BadXMLRefParamType = 1580, WRN_BadXMLRefReturnType = 1581, ERR_BadWin32Res = 1583, WRN_BadXMLRefSyntax = 1584, ERR_BadModifierLocation = 1585, ERR_MissingArraySize = 1586, WRN_UnprocessedXMLComment = 1587, //ERR_CantGetCORSystemDir = 1588, WRN_FailedInclude = 1589, WRN_InvalidInclude = 1590, WRN_MissingXMLComment = 1591, WRN_XMLParseIncludeError = 1592, ERR_BadDelArgCount = 1593, //ERR_BadDelArgTypes = 1594, WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1595"" is specified on the command line. WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1596"" is specified on the command line. ERR_UnexpectedSemicolon = 1597, WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time). ERR_MethodReturnCantBeRefAny = 1599, ERR_CompileCancelled = 1600, ERR_MethodArgCantBeRefAny = 1601, ERR_AssgReadonlyLocal = 1604, ERR_RefReadonlyLocal = 1605, //ERR_ALinkCloseFailed = 1606, WRN_ALinkWarn = 1607, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1607"" is specified on the command line. ERR_CantUseRequiredAttribute = 1608, ERR_NoModifiersOnAccessor = 1609, WRN_DeleteAutoResFailed = 1610, // Unused but preserving for /nowarn ERR_ParamsCantBeRefOut = 1611, ERR_ReturnNotLValue = 1612, ERR_MissingCoClass = 1613, ERR_AmbiguousAttribute = 1614, ERR_BadArgExtraRef = 1615, WRN_CmdOptionConflictsSource = 1616, ERR_BadCompatMode = 1617, ERR_DelegateOnConditional = 1618, //ERR_CantMakeTempFile = 1619, ERR_BadArgRef = 1620, ERR_YieldInAnonMeth = 1621, ERR_ReturnInIterator = 1622, ERR_BadIteratorArgType = 1623, ERR_BadIteratorReturn = 1624, ERR_BadYieldInFinally = 1625, ERR_BadYieldInTryOfCatch = 1626, ERR_EmptyYield = 1627, ERR_AnonDelegateCantUse = 1628, ERR_IllegalInnerUnsafe = 1629, //ERR_BadWatsonMode = 1630, ERR_BadYieldInCatch = 1631, ERR_BadDelegateLeave = 1632, WRN_IllegalPragma = 1633, WRN_IllegalPPWarning = 1634, WRN_BadRestoreNumber = 1635, ERR_VarargsIterator = 1636, ERR_UnsafeIteratorArgType = 1637, //ERR_ReservedIdentifier = 1638, ERR_BadCoClassSig = 1639, ERR_MultipleIEnumOfT = 1640, ERR_FixedDimsRequired = 1641, ERR_FixedNotInStruct = 1642, ERR_AnonymousReturnExpected = 1643, ERR_NonECMAFeature = 1644, WRN_NonECMAFeature = 1645, ERR_ExpectedVerbatimLiteral = 1646, //FTL_StackOverflow = 1647, ERR_AssgReadonly2 = 1648, ERR_RefReadonly2 = 1649, ERR_AssgReadonlyStatic2 = 1650, ERR_RefReadonlyStatic2 = 1651, ERR_AssgReadonlyLocal2Cause = 1654, ERR_RefReadonlyLocal2Cause = 1655, ERR_AssgReadonlyLocalCause = 1656, ERR_RefReadonlyLocalCause = 1657, WRN_ErrorOverride = 1658, WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1659"" is specified on the command line. ERR_AnonMethToNonDel = 1660, ERR_CantConvAnonMethParams = 1661, ERR_CantConvAnonMethReturns = 1662, ERR_IllegalFixedType = 1663, ERR_FixedOverflow = 1664, ERR_InvalidFixedArraySize = 1665, ERR_FixedBufferNotFixed = 1666, ERR_AttributeNotOnAccessor = 1667, WRN_InvalidSearchPathDir = 1668, ERR_IllegalVarArgs = 1669, ERR_IllegalParams = 1670, ERR_BadModifiersOnNamespace = 1671, ERR_BadPlatformType = 1672, ERR_ThisStructNotInAnonMeth = 1673, ERR_NoConvToIDisp = 1674, // ERR_InvalidGenericEnum = 1675, replaced with 7002 ERR_BadParamRef = 1676, ERR_BadParamExtraRef = 1677, ERR_BadParamType = 1678, ERR_BadExternIdentifier = 1679, ERR_AliasMissingFile = 1680, ERR_GlobalExternAlias = 1681, WRN_MissingTypeNested = 1682, //unused in Roslyn. // 1683 and 1684 are unused warning codes, but we still need to retain them to suppress CS1691 when ""/nowarn:1683"" is specified on the command line. // In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively. WRN_MissingTypeInSource = 1683, WRN_MissingTypeInAssembly = 1684, WRN_MultiplePredefTypes = 1685, ERR_LocalCantBeFixedAndHoisted = 1686, WRN_TooManyLinesForDebugger = 1687, ERR_CantConvAnonMethNoParams = 1688, ERR_ConditionalOnNonAttributeClass = 1689, WRN_CallOnNonAgileField = 1690, WRN_BadWarningNumber = 1691, WRN_InvalidNumber = 1692, WRN_FileNameTooLong = 1694, //unused but preserving for the sake of existing code using /nowarn:1694 WRN_IllegalPPChecksum = 1695, WRN_EndOfPPLineExpected = 1696, WRN_ConflictingChecksum = 1697, WRN_AssumedMatchThis = 1698, WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1699"" is specified. WRN_InvalidAssemblyName = 1700, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1700"" is specified. WRN_UnifyReferenceMajMin = 1701, WRN_UnifyReferenceBldRev = 1702, ERR_DuplicateImport = 1703, ERR_DuplicateImportSimple = 1704, ERR_AssemblyMatchBadVersion = 1705, ERR_AnonMethNotAllowed = 1706, WRN_DelegateNewMethBind = 1707, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1707"" is specified. ERR_FixedNeedsLvalue = 1708, WRN_EmptyFileName = 1709, WRN_DuplicateTypeParamTag = 1710, WRN_UnmatchedTypeParamTag = 1711, WRN_MissingTypeParamTag = 1712, //FTL_TypeNameBuilderError = 1713, ERR_ImportBadBase = 1714, ERR_CantChangeTypeOnOverride = 1715, ERR_DoNotUseFixedBufferAttr = 1716, WRN_AssignmentToSelf = 1717, WRN_ComparisonToSelf = 1718, ERR_CantOpenWin32Res = 1719, WRN_DotOnDefault = 1720, ERR_NoMultipleInheritance = 1721, ERR_BaseClassMustBeFirst = 1722, WRN_BadXMLRefTypeVar = 1723, //ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn. ERR_FriendAssemblyBadArgs = 1725, ERR_FriendAssemblySNReq = 1726, //ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings. ERR_DelegateOnNullable = 1728, ERR_BadCtorArgCount = 1729, ERR_GlobalAttributesNotFirst = 1730, ERR_CantConvAnonMethReturnsNoDelegate = 1731, //ERR_ParameterExpected = 1732, Not used in Roslyn. ERR_ExpressionExpected = 1733, WRN_UnmatchedParamRefTag = 1734, WRN_UnmatchedTypeParamRefTag = 1735, ERR_DefaultValueMustBeConstant = 1736, ERR_DefaultValueBeforeRequiredValue = 1737, ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738, ERR_BadNamedArgument = 1739, ERR_DuplicateNamedArgument = 1740, ERR_RefOutDefaultValue = 1741, ERR_NamedArgumentForArray = 1742, ERR_DefaultValueForExtensionParameter = 1743, ERR_NamedArgumentUsedInPositional = 1744, ERR_DefaultValueUsedWithAttributes = 1745, ERR_BadNamedArgumentForDelegateInvoke = 1746, ERR_NoPIAAssemblyMissingAttribute = 1747, ERR_NoCanonicalView = 1748, //ERR_TypeNotFoundForNoPIA = 1749, ERR_NoConversionForDefaultParam = 1750, ERR_DefaultValueForParamsParameter = 1751, ERR_NewCoClassOnLink = 1752, ERR_NoPIANestedType = 1754, //ERR_InvalidTypeIdentifierConstructor = 1755, ERR_InteropTypeMissingAttribute = 1756, ERR_InteropStructContainsMethods = 1757, ERR_InteropTypesWithSameNameAndGuid = 1758, ERR_NoPIAAssemblyMissingAttributes = 1759, ERR_AssemblySpecifiedForLinkAndRef = 1760, ERR_LocalTypeNameClash = 1761, WRN_ReferencedAssemblyReferencesLinkedPIA = 1762, ERR_NotNullRefDefaultParameter = 1763, ERR_FixedLocalInLambda = 1764, WRN_TypeNotFoundForNoPIAWarning = 1765, ERR_MissingMethodOnSourceInterface = 1766, ERR_MissingSourceInterface = 1767, ERR_GenericsUsedInNoPIAType = 1768, ERR_GenericsUsedAcrossAssemblies = 1769, ERR_NoConversionForNubDefaultParam = 1770, //ERR_MemberWithGenericsUsedAcrossAssemblies = 1771, //ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772, ERR_BadSubsystemVersion = 1773, ERR_InteropMethodWithBody = 1774, ERR_BadWarningLevel = 1900, ERR_BadDebugType = 1902, //ERR_UnknownTestSwitch = 1903, ERR_BadResourceVis = 1906, ERR_DefaultValueTypeMustMatch = 1908, //ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn. ERR_DefaultValueBadValueType = 1910, ERR_MemberAlreadyInitialized = 1912, ERR_MemberCannotBeInitialized = 1913, ERR_StaticMemberInObjectInitializer = 1914, ERR_ReadonlyValueTypeInObjectInitializer = 1917, ERR_ValueTypePropertyInObjectInitializer = 1918, ERR_UnsafeTypeInObjectCreation = 1919, ERR_EmptyElementInitializer = 1920, ERR_InitializerAddHasWrongSignature = 1921, ERR_CollectionInitRequiresIEnumerable = 1922, ERR_InvalidCollectionInitializerType = 1925, ERR_CantOpenWin32Manifest = 1926, WRN_CantHaveManifestForModule = 1927, ERR_BadExtensionArgTypes = 1928, ERR_BadInstanceArgType = 1929, ERR_QueryDuplicateRangeVariable = 1930, ERR_QueryRangeVariableOverrides = 1931, ERR_QueryRangeVariableAssignedBadValue = 1932, ERR_QueryNotAllowed = 1933, ERR_QueryNoProviderCastable = 1934, ERR_QueryNoProviderStandard = 1935, ERR_QueryNoProvider = 1936, ERR_QueryOuterKey = 1937, ERR_QueryInnerKey = 1938, ERR_QueryOutRefRangeVariable = 1939, ERR_QueryMultipleProviders = 1940, ERR_QueryTypeInferenceFailedMulti = 1941, ERR_QueryTypeInferenceFailed = 1942, ERR_QueryTypeInferenceFailedSelectMany = 1943, ERR_ExpressionTreeContainsPointerOp = 1944, ERR_ExpressionTreeContainsAnonymousMethod = 1945, ERR_AnonymousMethodToExpressionTree = 1946, ERR_QueryRangeVariableReadOnly = 1947, ERR_QueryRangeVariableSameAsTypeParam = 1948, ERR_TypeVarNotFoundRangeVariable = 1949, ERR_BadArgTypesForCollectionAdd = 1950, ERR_ByRefParameterInExpressionTree = 1951, ERR_VarArgsInExpressionTree = 1952, ERR_MemGroupInExpressionTree = 1953, ERR_InitializerAddHasParamModifiers = 1954, ERR_NonInvocableMemberCalled = 1955, WRN_MultipleRuntimeImplementationMatches = 1956, WRN_MultipleRuntimeOverrideMatches = 1957, ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958, ERR_InvalidConstantDeclarationType = 1959, ERR_IllegalVarianceSyntax = 1960, ERR_UnexpectedVariance = 1961, ERR_BadDynamicTypeof = 1962, ERR_ExpressionTreeContainsDynamicOperation = 1963, ERR_BadDynamicConversion = 1964, ERR_DeriveFromDynamic = 1965, ERR_DeriveFromConstructedDynamic = 1966, ERR_DynamicTypeAsBound = 1967, ERR_ConstructedDynamicTypeAsBound = 1968, ERR_DynamicRequiredTypesMissing = 1969, ERR_ExplicitDynamicAttr = 1970, ERR_NoDynamicPhantomOnBase = 1971, ERR_NoDynamicPhantomOnBaseIndexer = 1972, ERR_BadArgTypeDynamicExtension = 1973, WRN_DynamicDispatchToConditionalMethod = 1974, ERR_NoDynamicPhantomOnBaseCtor = 1975, ERR_BadDynamicMethodArgMemgrp = 1976, ERR_BadDynamicMethodArgLambda = 1977, ERR_BadDynamicMethodArg = 1978, ERR_BadDynamicQuery = 1979, ERR_DynamicAttributeMissing = 1980, WRN_IsDynamicIsConfusing = 1981, ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn. ERR_BadAsyncReturn = 1983, ERR_BadAwaitInFinally = 1984, ERR_BadAwaitInCatch = 1985, ERR_BadAwaitArg = 1986, ERR_BadAsyncArgType = 1988, ERR_BadAsyncExpressionTree = 1989, ERR_WindowsRuntimeTypesMissing = 1990, ERR_MixingWinRTEventWithRegular = 1991, ERR_BadAwaitWithoutAsync = 1992, ERR_MissingAsyncTypes = 1993, ERR_BadAsyncLacksBody = 1994, ERR_BadAwaitInQuery = 1995, ERR_BadAwaitInLock = 1996, ERR_TaskRetNoObjectRequired = 1997, WRN_AsyncLacksAwaits = 1998, ERR_FileNotFound = 2001, WRN_FileAlreadyIncluded = 2002, ERR_DuplicateResponseFile = 2003, ERR_NoFileSpec = 2005, ERR_SwitchNeedsString = 2006, ERR_BadSwitch = 2007, WRN_NoSources = 2008, ERR_OpenResponseFile = 2011, ERR_CantOpenFileWrite = 2012, ERR_BadBaseNumber = 2013, WRN_UseNewSwitch = 2014, //unused but preserved to keep compat with /nowarn:2014 ERR_BinaryFile = 2015, FTL_BadCodepage = 2016, ERR_NoMainOnDLL = 2017, //FTL_NoMessagesDLL = 2018, FTL_InvalidTarget = 2019, //ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once! FTL_InvalidInputFileName = 2021, //ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once! WRN_NoConfigNotOnCommandLine = 2023, ERR_BadFileAlignment = 2024, //ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn. //ERR_SourceMapFileBinary = 2027, WRN_DefineIdentifierRequired = 2029, //ERR_InvalidSourceMap = 2030, //ERR_NoSourceMapFile = 2031, ERR_IllegalOptionChar = 2032, FTL_OutputFileExists = 2033, ERR_OneAliasPerReference = 2034, ERR_SwitchNeedsNumber = 2035, ERR_MissingDebugSwitch = 2036, ERR_ComRefCallInExpressionTree = 2037, WRN_BadUILang = 2038, WRN_CLS_NoVarArgs = 3000, WRN_CLS_BadArgType = 3001, WRN_CLS_BadReturnType = 3002, WRN_CLS_BadFieldPropType = 3003, WRN_CLS_BadUnicode = 3004, //unused but preserved to keep compat with /nowarn:3004 WRN_CLS_BadIdentifierCase = 3005, WRN_CLS_OverloadRefOut = 3006, WRN_CLS_OverloadUnnamed = 3007, WRN_CLS_BadIdentifier = 3008, WRN_CLS_BadBase = 3009, WRN_CLS_BadInterfaceMember = 3010, WRN_CLS_NoAbstractMembers = 3011, WRN_CLS_NotOnModules = 3012, WRN_CLS_ModuleMissingCLS = 3013, WRN_CLS_AssemblyNotCLS = 3014, WRN_CLS_BadAttributeType = 3015, WRN_CLS_ArrayArgumentToAttribute = 3016, WRN_CLS_NotOnModules2 = 3017, WRN_CLS_IllegalTrueInFalse = 3018, WRN_CLS_MeaninglessOnPrivateType = 3019, WRN_CLS_AssemblyNotCLS2 = 3021, WRN_CLS_MeaninglessOnParam = 3022, WRN_CLS_MeaninglessOnReturn = 3023, WRN_CLS_BadTypeVar = 3024, WRN_CLS_VolatileField = 3026, WRN_CLS_BadInterface = 3027, // Errors introduced in C# 5 are in the range 4000-4999 // 4000 unused ERR_BadAwaitArgIntrinsic = 4001, // 4002 unused ERR_BadAwaitAsIdentifier = 4003, ERR_AwaitInUnsafeContext = 4004, ERR_UnsafeAsyncArgType = 4005, ERR_VarargsAsync = 4006, ERR_ByRefTypeAndAwait = 4007, ERR_BadAwaitArgVoidCall = 4008, ERR_MainCantBeAsync = 4009, ERR_CantConvAsyncAnonFuncReturns = 4010, ERR_BadAwaiterPattern = 4011, ERR_BadSpecialByRefLocal = 4012, ERR_SpecialByRefInLambda = 4013, WRN_UnobservedAwaitableExpression = 4014, ERR_SynchronizedAsyncMethod = 4015, ERR_BadAsyncReturnExpression = 4016, ERR_NoConversionForCallerLineNumberParam = 4017, ERR_NoConversionForCallerFilePathParam = 4018, ERR_NoConversionForCallerMemberNameParam = 4019, ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020, ERR_BadCallerFilePathParamWithoutDefaultValue = 4021, ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022, ERR_BadPrefer32OnLib = 4023, WRN_CallerLineNumberParamForUnconsumedLocation = 4024, WRN_CallerFilePathParamForUnconsumedLocation = 4025, WRN_CallerMemberNameParamForUnconsumedLocation = 4026, ERR_DoesntImplementAwaitInterface = 4027, ERR_BadAwaitArg_NeedSystem = 4028, ERR_CantReturnVoid = 4029, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031, ERR_BadAwaitWithoutAsyncMethod = 4032, ERR_BadAwaitWithoutVoidAsyncMethod = 4033, ERR_BadAwaitWithoutAsyncLambda = 4034, // ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn ERR_NoSuchMemberOrExtensionNeedUsing = 4036, WRN_UnknownOption = 5000, //unused in Roslyn ERR_NoEntryPoint = 5001, // There is space in the range of error codes from 7000-8999 that // we can use for new errors in post-Dev10. ERR_UnexpectedAliasedName = 7000, ERR_UnexpectedGenericName = 7002, ERR_UnexpectedUnboundGenericName = 7003, ERR_GlobalStatement = 7006, ERR_BadUsingType = 7007, ERR_ReservedAssemblyName = 7008, ERR_PPReferenceFollowsToken = 7009, ERR_ExpectedPPFile = 7010, ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011, ERR_NameNotInContextPossibleMissingReference = 7012, WRN_MetadataNameTooLong = 7013, ERR_AttributesNotAllowed = 7014, ERR_ExternAliasNotAllowed = 7015, ERR_ConflictingAliasAndDefinition = 7016, ERR_GlobalDefinitionOrStatementExpected = 7017, ERR_ExpectedSingleScript = 7018, ERR_RecursivelyTypedVariable = 7019, ERR_ReturnNotAllowedInScript = 7020, ERR_NamespaceNotAllowedInScript = 7021, WRN_MainIgnored = 7022, ERR_StaticInAsOrIs = 7023, ERR_InvalidDelegateType = 7024, ERR_BadVisEventType = 7025, ERR_GlobalAttributesNotAllowed = 7026, ERR_PublicKeyFileFailure = 7027, ERR_PublicKeyContainerFailure = 7028, ERR_FriendRefSigningMismatch = 7029, ERR_CannotPassNullForFriendAssembly = 7030, ERR_SignButNoPrivateKey = 7032, WRN_DelaySignButNoKey = 7033, ERR_InvalidVersionFormat = 7034, WRN_InvalidVersionFormat = 7035, ERR_NoCorrespondingArgument = 7036, // Moot: WRN_DestructorIsNotFinalizer = 7037, ERR_ModuleEmitFailure = 7038, ERR_NameIllegallyOverrides2 = 7039, ERR_NameIllegallyOverrides3 = 7040, ERR_ResourceFileNameNotUnique = 7041, ERR_DllImportOnGenericMethod = 7042, ERR_LibraryMethodNotFound = 7043, ERR_LibraryMethodNotUnique = 7044, ERR_ParameterNotValidForType = 7045, ERR_AttributeParameterRequired1 = 7046, ERR_AttributeParameterRequired2 = 7047, ERR_SecurityAttributeMissingAction = 7048, ERR_SecurityAttributeInvalidAction = 7049, ERR_SecurityAttributeInvalidActionAssembly = 7050, ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051, ERR_PrincipalPermissionInvalidAction = 7052, ERR_FeatureNotValidInExpressionTree = 7053, ERR_MarshalUnmanagedTypeNotValidForFields = 7054, ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055, ERR_PermissionSetAttributeInvalidFile = 7056, ERR_PermissionSetAttributeFileReadError = 7057, ERR_InvalidVersionFormat2 = 7058, ERR_InvalidAssemblyCultureForExe = 7059, ERR_AsyncBeforeVersionFive = 7060, ERR_DuplicateAttributeInNetModule = 7061, //WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning ERR_CantOpenIcon = 7064, ERR_ErrorBuildingWin32Resources = 7065, ERR_IteratorInInteractive = 7066, ERR_BadAttributeParamDefaultArgument = 7067, ERR_MissingTypeInSource = 7068, ERR_MissingTypeInAssembly = 7069, ERR_SecurityAttributeInvalidTarget = 7070, ERR_InvalidAssemblyName = 7071, ERR_PartialTypesBeforeVersionTwo = 7072, ERR_PartialMethodsBeforeVersionThree = 7073, ERR_QueryBeforeVersionThree = 7074, ERR_AnonymousTypeBeforeVersionThree = 7075, ERR_ImplicitArrayBeforeVersionThree = 7076, ERR_ObjectInitializerBeforeVersionThree = 7077, ERR_LambdaBeforeVersionThree = 7078, ERR_NoTypeDefFromModule = 7079, WRN_CallerFilePathPreferredOverCallerMemberName = 7080, WRN_CallerLineNumberPreferredOverCallerMemberName = 7081, WRN_CallerLineNumberPreferredOverCallerFilePath = 7082, ERR_InvalidDynamicCondition = 7083, ERR_WinRtEventPassedByRef = 7084, ERR_ByRefReturnUnsupported = 7085, ERR_NetModuleNameMismatch = 7086, ERR_BadCompilationOption = 7087, ERR_BadCompilationOptionValue = 7088, ERR_BadAppConfigPath = 7089, WRN_AssemblyAttributeFromModuleIsOverridden = 7090, ERR_CmdOptionConflictsSource = 7091, ERR_FixedBufferTooManyDimensions = 7092, ERR_CantReadConfigFile = 7093, ERR_NotYetImplementedInRoslyn = 8000, WRN_UnimplementedCommandLineSwitch = 8001, ERR_ReferencedAssemblyDoesNotHaveStrongName = 8002, ERR_InvalidSignaturePublicKey = 8003, ERR_ExportedTypeConflictsWithDeclaration = 8004, ERR_ExportedTypesConflict = 8005, ERR_ForwardedTypeConflictsWithDeclaration = 8006, ERR_ForwardedTypesConflict = 8007, ERR_ForwardedTypeConflictsWithExportedType = 8008, WRN_RefCultureMismatch = 8009, ERR_AgnosticToMachineModule = 8010, ERR_ConflictingMachineModule = 8011, WRN_ConflictingMachineAssembly = 8012, ERR_CryptoHashFailed = 8013, ERR_MissingNetModuleReference = 8014, // Values in the range 10000-14000 are used for ""Code Analysis"" issues previously reported by FXCop WRN_CA2000_DisposeObjectsBeforeLosingScope1 = 10000, WRN_CA2000_DisposeObjectsBeforeLosingScope2 = 10001, WRN_CA2202_DoNotDisposeObjectsMultipleTimes = 10002 } /// <summary> /// Values for ErrorCode/ERRID that are used internally by the compiler but are not exposed. /// </summary> internal static class InternalErrorCode { /// <summary> /// The code has yet to be determined. /// </summary> public const int Unknown = -1; /// <summary> /// The code was lazily determined and does not need to be reported. /// </summary> public const int Void = -2; } } } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyIL("ConsoleApplication24.Program.IsWarning", @" { // Code size 1889 (0x761) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4 0x32b IL_0006: bgt IL_0300 IL_000b: ldarg.0 IL_000c: ldc.i4 0x1ad IL_0011: bgt IL_0154 IL_0016: ldarg.0 IL_0017: ldc.i4 0xb8 IL_001c: bgt IL_00a9 IL_0021: ldarg.0 IL_0022: ldc.i4.s 109 IL_0024: bgt.s IL_005f IL_0026: ldarg.0 IL_0027: ldc.i4.s 67 IL_0029: bgt.s IL_0040 IL_002b: ldarg.0 IL_002c: ldc.i4.s 28 IL_002e: beq IL_075d IL_0033: ldarg.0 IL_0034: ldc.i4.s 67 IL_0036: beq IL_075d IL_003b: br IL_075f IL_0040: ldarg.0 IL_0041: ldc.i4.s 78 IL_0043: beq IL_075d IL_0048: ldarg.0 IL_0049: ldc.i4.s 105 IL_004b: beq IL_075d IL_0050: ldarg.0 IL_0051: ldc.i4.s 108 IL_0053: sub IL_0054: ldc.i4.1 IL_0055: ble.un IL_075d IL_005a: br IL_075f IL_005f: ldarg.0 IL_0060: ldc.i4 0xa2 IL_0065: bgt.s IL_007f IL_0067: ldarg.0 IL_0068: ldc.i4.s 114 IL_006a: beq IL_075d IL_006f: ldarg.0 IL_0070: ldc.i4 0xa2 IL_0075: beq IL_075d IL_007a: br IL_075f IL_007f: ldarg.0 IL_0080: ldc.i4 0xa4 IL_0085: beq IL_075d IL_008a: ldarg.0 IL_008b: ldc.i4 0xa8 IL_0090: sub IL_0091: ldc.i4.1 IL_0092: ble.un IL_075d IL_0097: ldarg.0 IL_0098: ldc.i4 0xb7 IL_009d: sub IL_009e: ldc.i4.1 IL_009f: ble.un IL_075d IL_00a4: br IL_075f IL_00a9: ldarg.0 IL_00aa: ldc.i4 0x118 IL_00af: bgt.s IL_00fe IL_00b1: ldarg.0 IL_00b2: ldc.i4 0xcf IL_00b7: bgt.s IL_00d4 IL_00b9: ldarg.0 IL_00ba: ldc.i4 0xc5 IL_00bf: beq IL_075d IL_00c4: ldarg.0 IL_00c5: ldc.i4 0xcf IL_00ca: beq IL_075d IL_00cf: br IL_075f IL_00d4: ldarg.0 IL_00d5: ldc.i4 0xdb IL_00da: beq IL_075d IL_00df: ldarg.0 IL_00e0: ldc.i4 0xfb IL_00e5: sub IL_00e6: ldc.i4.2 IL_00e7: ble.un IL_075d IL_00ec: ldarg.0 IL_00ed: ldc.i4 0x116 IL_00f2: sub IL_00f3: ldc.i4.2 IL_00f4: ble.un IL_075d IL_00f9: br IL_075f IL_00fe: ldarg.0 IL_00ff: ldc.i4 0x19e IL_0104: bgt.s IL_012c IL_0106: ldarg.0 IL_0107: ldc.i4 0x11a IL_010c: beq IL_075d IL_0111: ldarg.0 IL_0112: ldc.i4 0x192 IL_0117: beq IL_075d IL_011c: ldarg.0 IL_011d: ldc.i4 0x19e IL_0122: beq IL_075d IL_0127: br IL_075f IL_012c: ldarg.0 IL_012d: ldc.i4 0x1a3 IL_0132: sub IL_0133: ldc.i4.1 IL_0134: ble.un IL_075d IL_0139: ldarg.0 IL_013a: ldc.i4 0x1a6 IL_013f: beq IL_075d IL_0144: ldarg.0 IL_0145: ldc.i4 0x1ad IL_014a: beq IL_075d IL_014f: br IL_075f IL_0154: ldarg.0 IL_0155: ldc.i4 0x274 IL_015a: bgt IL_0224 IL_015f: ldarg.0 IL_0160: ldc.i4 0x1d9 IL_0165: bgt.s IL_01db IL_0167: ldarg.0 IL_0168: ldc.i4 0x1b8 IL_016d: bgt.s IL_018c IL_016f: ldarg.0 IL_0170: ldc.i4 0x1b3 IL_0175: sub IL_0176: ldc.i4.2 IL_0177: ble.un IL_075d IL_017c: ldarg.0 IL_017d: ldc.i4 0x1b8 IL_0182: beq IL_075d IL_0187: br IL_075f IL_018c: ldarg.0 IL_018d: ldc.i4 0x1bc IL_0192: beq IL_075d IL_0197: ldarg.0 IL_0198: ldc.i4 0x1ca IL_019d: beq IL_075d IL_01a2: ldarg.0 IL_01a3: ldc.i4 0x1d0 IL_01a8: sub IL_01a9: switch ( IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d) IL_01d6: br IL_075f IL_01db: ldarg.0 IL_01dc: ldc.i4 0x264 IL_01e1: bgt.s IL_01fe IL_01e3: ldarg.0 IL_01e4: ldc.i4 0x25a IL_01e9: beq IL_075d IL_01ee: ldarg.0 IL_01ef: ldc.i4 0x264 IL_01f4: beq IL_075d IL_01f9: br IL_075f IL_01fe: ldarg.0 IL_01ff: ldc.i4 0x26a IL_0204: beq IL_075d IL_0209: ldarg.0 IL_020a: ldc.i4 0x272 IL_020f: beq IL_075d IL_0214: ldarg.0 IL_0215: ldc.i4 0x274 IL_021a: beq IL_075d IL_021f: br IL_075f IL_0224: ldarg.0 IL_0225: ldc.i4 0x2a3 IL_022a: bgt.s IL_02aa IL_022c: ldarg.0 IL_022d: ldc.i4 0x295 IL_0232: bgt.s IL_0284 IL_0234: ldarg.0 IL_0235: ldc.i4 0x282 IL_023a: beq IL_075d IL_023f: ldarg.0 IL_0240: ldc.i4 0x289 IL_0245: sub IL_0246: switch ( IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d) IL_027f: br IL_075f IL_0284: ldarg.0 IL_0285: ldc.i4 0x299 IL_028a: beq IL_075d IL_028f: ldarg.0 IL_0290: ldc.i4 0x2a0 IL_0295: beq IL_075d IL_029a: ldarg.0 IL_029b: ldc.i4 0x2a3 IL_02a0: beq IL_075d IL_02a5: br IL_075f IL_02aa: ldarg.0 IL_02ab: ldc.i4 0x2b5 IL_02b0: bgt.s IL_02da IL_02b2: ldarg.0 IL_02b3: ldc.i4 0x2a7 IL_02b8: sub IL_02b9: ldc.i4.1 IL_02ba: ble.un IL_075d IL_02bf: ldarg.0 IL_02c0: ldc.i4 0x2ac IL_02c5: beq IL_075d IL_02ca: ldarg.0 IL_02cb: ldc.i4 0x2b5 IL_02d0: beq IL_075d IL_02d5: br IL_075f IL_02da: ldarg.0 IL_02db: ldc.i4 0x2d8 IL_02e0: beq IL_075d IL_02e5: ldarg.0 IL_02e6: ldc.i4 0x329 IL_02eb: beq IL_075d IL_02f0: ldarg.0 IL_02f1: ldc.i4 0x32b IL_02f6: beq IL_075d IL_02fb: br IL_075f IL_0300: ldarg.0 IL_0301: ldc.i4 0x7bd IL_0306: bgt IL_05d1 IL_030b: ldarg.0 IL_030c: ldc.i4 0x663 IL_0311: bgt IL_0451 IL_0316: ldarg.0 IL_0317: ldc.i4 0x5f2 IL_031c: bgt.s IL_038e IL_031e: ldarg.0 IL_031f: ldc.i4 0x406 IL_0324: bgt.s IL_0341 IL_0326: ldarg.0 IL_0327: ldc.i4 0x338 IL_032c: beq IL_075d IL_0331: ldarg.0 IL_0332: ldc.i4 0x406 IL_0337: beq IL_075d IL_033c: br IL_075f IL_0341: ldarg.0 IL_0342: ldc.i4 0x422 IL_0347: sub IL_0348: switch ( IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d, IL_075f, IL_075d) IL_0371: ldarg.0 IL_0372: ldc.i4 0x4b0 IL_0377: sub IL_0378: ldc.i4.4 IL_0379: ble.un IL_075d IL_037e: ldarg.0 IL_037f: ldc.i4 0x5f2 IL_0384: beq IL_075d IL_0389: br IL_075f IL_038e: ldarg.0 IL_038f: ldc.i4 0x647 IL_0394: bgt IL_0429 IL_0399: ldarg.0 IL_039a: ldc.i4 0x622 IL_039f: sub IL_03a0: switch ( IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d, IL_075f, IL_075d) IL_0419: ldarg.0 IL_041a: ldc.i4 0x647 IL_041f: beq IL_075d IL_0424: br IL_075f IL_0429: ldarg.0 IL_042a: ldc.i4 0x64a IL_042f: beq IL_075d IL_0434: ldarg.0 IL_0435: ldc.i4 0x650 IL_043a: beq IL_075d IL_043f: ldarg.0 IL_0440: ldc.i4 0x661 IL_0445: sub IL_0446: ldc.i4.2 IL_0447: ble.un IL_075d IL_044c: br IL_075f IL_0451: ldarg.0 IL_0452: ldc.i4 0x6c7 IL_0457: bgt IL_057b IL_045c: ldarg.0 IL_045d: ldc.i4 0x67b IL_0462: bgt.s IL_0481 IL_0464: ldarg.0 IL_0465: ldc.i4 0x66d IL_046a: beq IL_075d IL_046f: ldarg.0 IL_0470: ldc.i4 0x67a IL_0475: sub IL_0476: ldc.i4.1 IL_0477: ble.un IL_075d IL_047c: br IL_075f IL_0481: ldarg.0 IL_0482: ldc.i4 0x684 IL_0487: sub IL_0488: switch ( IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075f, IL_075f, IL_075f, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d) IL_0541: ldarg.0 IL_0542: ldc.i4 0x6b5 IL_0547: sub IL_0548: switch ( IL_075d, IL_075d, IL_075f, IL_075d, IL_075f, IL_075f, IL_075d) IL_0569: ldarg.0 IL_056a: ldc.i4 0x6c6 IL_056f: sub IL_0570: ldc.i4.1 IL_0571: ble.un IL_075d IL_0576: br IL_075f IL_057b: ldarg.0 IL_057c: ldc.i4 0x787 IL_0581: bgt.s IL_05a9 IL_0583: ldarg.0 IL_0584: ldc.i4 0x6e2 IL_0589: beq IL_075d IL_058e: ldarg.0 IL_058f: ldc.i4 0x6e5 IL_0594: beq IL_075d IL_0599: ldarg.0 IL_059a: ldc.i4 0x787 IL_059f: beq IL_075d IL_05a4: br IL_075f IL_05a9: ldarg.0 IL_05aa: ldc.i4 0x7a4 IL_05af: sub IL_05b0: ldc.i4.1 IL_05b1: ble.un IL_075d IL_05b6: ldarg.0 IL_05b7: ldc.i4 0x7b6 IL_05bc: beq IL_075d IL_05c1: ldarg.0 IL_05c2: ldc.i4 0x7bd IL_05c7: beq IL_075d IL_05cc: br IL_075f IL_05d1: ldarg.0 IL_05d2: ldc.i4 0xfba IL_05d7: bgt IL_06e3 IL_05dc: ldarg.0 IL_05dd: ldc.i4 0x7e7 IL_05e2: bgt.s IL_062d IL_05e4: ldarg.0 IL_05e5: ldc.i4 0x7d2 IL_05ea: bgt.s IL_0607 IL_05ec: ldarg.0 IL_05ed: ldc.i4 0x7ce IL_05f2: beq IL_075d IL_05f7: ldarg.0 IL_05f8: ldc.i4 0x7d2 IL_05fd: beq IL_075d IL_0602: br IL_075f IL_0607: ldarg.0 IL_0608: ldc.i4 0x7d8 IL_060d: beq IL_075d IL_0612: ldarg.0 IL_0613: ldc.i4 0x7de IL_0618: beq IL_075d IL_061d: ldarg.0 IL_061e: ldc.i4 0x7e7 IL_0623: beq IL_075d IL_0628: br IL_075f IL_062d: ldarg.0 IL_062e: ldc.i4 0x7f6 IL_0633: bgt.s IL_0650 IL_0635: ldarg.0 IL_0636: ldc.i4 0x7ed IL_063b: beq IL_075d IL_0640: ldarg.0 IL_0641: ldc.i4 0x7f6 IL_0646: beq IL_075d IL_064b: br IL_075f IL_0650: ldarg.0 IL_0651: ldc.i4 0xbb8 IL_0656: sub IL_0657: switch ( IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d, IL_075d, IL_075d, IL_075f, IL_075d, IL_075d) IL_06cc: ldarg.0 IL_06cd: ldc.i4 0xfae IL_06d2: beq IL_075d IL_06d7: ldarg.0 IL_06d8: ldc.i4 0xfb8 IL_06dd: sub IL_06de: ldc.i4.2 IL_06df: ble.un.s IL_075d IL_06e1: br.s IL_075f IL_06e3: ldarg.0 IL_06e4: ldc.i4 0x1b7b IL_06e9: bgt.s IL_071f IL_06eb: ldarg.0 IL_06ec: ldc.i4 0x1b65 IL_06f1: bgt.s IL_0705 IL_06f3: ldarg.0 IL_06f4: ldc.i4 0x1388 IL_06f9: beq.s IL_075d IL_06fb: ldarg.0 IL_06fc: ldc.i4 0x1b65 IL_0701: beq.s IL_075d IL_0703: br.s IL_075f IL_0705: ldarg.0 IL_0706: ldc.i4 0x1b6e IL_070b: beq.s IL_075d IL_070d: ldarg.0 IL_070e: ldc.i4 0x1b79 IL_0713: beq.s IL_075d IL_0715: ldarg.0 IL_0716: ldc.i4 0x1b7b IL_071b: beq.s IL_075d IL_071d: br.s IL_075f IL_071f: ldarg.0 IL_0720: ldc.i4 0x1f41 IL_0725: bgt.s IL_0743 IL_0727: ldarg.0 IL_0728: ldc.i4 0x1ba8 IL_072d: sub IL_072e: ldc.i4.2 IL_072f: ble.un.s IL_075d IL_0731: ldarg.0 IL_0732: ldc.i4 0x1bb2 IL_0737: beq.s IL_075d IL_0739: ldarg.0 IL_073a: ldc.i4 0x1f41 IL_073f: beq.s IL_075d IL_0741: br.s IL_075f IL_0743: ldarg.0 IL_0744: ldc.i4 0x1f49 IL_0749: beq.s IL_075d IL_074b: ldarg.0 IL_074c: ldc.i4 0x1f4c IL_0751: beq.s IL_075d IL_0753: ldarg.0 IL_0754: ldc.i4 0x2710 IL_0759: sub IL_075a: ldc.i4.2 IL_075b: bgt.un.s IL_075f IL_075d: ldc.i4.1 IL_075e: ret IL_075f: ldc.i4.0 IL_0760: ret }"); } [Fact] public void StringSwitch() { var text = @"using System; public class Test { public static void Main() { Console.WriteLine(M(""Orange"")); } public static int M(string s) { switch (s) { case ""Black"": return 0; case ""Brown"": return 1; case ""Red"": return 2; case ""Orange"": return 3; case ""Yellow"": return 4; case ""Green"": return 5; case ""Blue"": return 6; case ""Violet"": return 7; case ""Grey"": case ""Gray"": return 8; case ""White"": return 9; default: throw new ArgumentException(s); } } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "3"); compVerifier.VerifyIL("Test.M", @" { // Code size 368 (0x170) .maxstack 2 .locals init (uint V_0) IL_0000: ldarg.0 IL_0001: call ""ComputeStringHash"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4 0x6ceb2d06 IL_000d: bgt.un.s IL_0055 IL_000f: ldloc.0 IL_0010: ldc.i4 0x2b043744 IL_0015: bgt.un.s IL_002f IL_0017: ldloc.0 IL_0018: ldc.i4 0x2b8b9cf IL_001d: beq IL_00b2 IL_0022: ldloc.0 IL_0023: ldc.i4 0x2b043744 IL_0028: beq.s IL_009d IL_002a: br IL_0169 IL_002f: ldloc.0 IL_0030: ldc.i4 0x32bdf8c6 IL_0035: beq IL_0127 IL_003a: ldloc.0 IL_003b: ldc.i4 0x3ac6ffba IL_0040: beq IL_0136 IL_0045: ldloc.0 IL_0046: ldc.i4 0x6ceb2d06 IL_004b: beq IL_0145 IL_0050: br IL_0169 IL_0055: ldloc.0 IL_0056: ldc.i4 0xa953c75c IL_005b: bgt.un.s IL_007d IL_005d: ldloc.0 IL_005e: ldc.i4 0x727b390b IL_0063: beq.s IL_00dc IL_0065: ldloc.0 IL_0066: ldc.i4 0xa37f187c IL_006b: beq.s IL_00c7 IL_006d: ldloc.0 IL_006e: ldc.i4 0xa953c75c IL_0073: beq IL_00fa IL_0078: br IL_0169 IL_007d: ldloc.0 IL_007e: ldc.i4 0xd9cdec69 IL_0083: beq.s IL_00eb IL_0085: ldloc.0 IL_0086: ldc.i4 0xe9dd1fed IL_008b: beq.s IL_0109 IL_008d: ldloc.0 IL_008e: ldc.i4 0xf03bdf12 IL_0093: beq IL_0118 IL_0098: br IL_0169 IL_009d: ldarg.0 IL_009e: ldstr ""Black"" IL_00a3: call ""bool string.op_Equality(string, string)"" IL_00a8: brtrue IL_0154 IL_00ad: br IL_0169 IL_00b2: ldarg.0 IL_00b3: ldstr ""Brown"" IL_00b8: call ""bool string.op_Equality(string, string)"" IL_00bd: brtrue IL_0156 IL_00c2: br IL_0169 IL_00c7: ldarg.0 IL_00c8: ldstr ""Red"" IL_00cd: call ""bool string.op_Equality(string, string)"" IL_00d2: brtrue IL_0158 IL_00d7: br IL_0169 IL_00dc: ldarg.0 IL_00dd: ldstr ""Orange"" IL_00e2: call ""bool string.op_Equality(string, string)"" IL_00e7: brtrue.s IL_015a IL_00e9: br.s IL_0169 IL_00eb: ldarg.0 IL_00ec: ldstr ""Yellow"" IL_00f1: call ""bool string.op_Equality(string, string)"" IL_00f6: brtrue.s IL_015c IL_00f8: br.s IL_0169 IL_00fa: ldarg.0 IL_00fb: ldstr ""Green"" IL_0100: call ""bool string.op_Equality(string, string)"" IL_0105: brtrue.s IL_015e IL_0107: br.s IL_0169 IL_0109: ldarg.0 IL_010a: ldstr ""Blue"" IL_010f: call ""bool string.op_Equality(string, string)"" IL_0114: brtrue.s IL_0160 IL_0116: br.s IL_0169 IL_0118: ldarg.0 IL_0119: ldstr ""Violet"" IL_011e: call ""bool string.op_Equality(string, string)"" IL_0123: brtrue.s IL_0162 IL_0125: br.s IL_0169 IL_0127: ldarg.0 IL_0128: ldstr ""Grey"" IL_012d: call ""bool string.op_Equality(string, string)"" IL_0132: brtrue.s IL_0164 IL_0134: br.s IL_0169 IL_0136: ldarg.0 IL_0137: ldstr ""Gray"" IL_013c: call ""bool string.op_Equality(string, string)"" IL_0141: brtrue.s IL_0164 IL_0143: br.s IL_0169 IL_0145: ldarg.0 IL_0146: ldstr ""White"" IL_014b: call ""bool string.op_Equality(string, string)"" IL_0150: brtrue.s IL_0166 IL_0152: br.s IL_0169 IL_0154: ldc.i4.0 IL_0155: ret IL_0156: ldc.i4.1 IL_0157: ret IL_0158: ldc.i4.2 IL_0159: ret IL_015a: ldc.i4.3 IL_015b: ret IL_015c: ldc.i4.4 IL_015d: ret IL_015e: ldc.i4.5 IL_015f: ret IL_0160: ldc.i4.6 IL_0161: ret IL_0162: ldc.i4.7 IL_0163: ret IL_0164: ldc.i4.8 IL_0165: ret IL_0166: ldc.i4.s 9 IL_0168: ret IL_0169: ldarg.0 IL_016a: newobj ""System.ArgumentException..ctor(string)"" IL_016f: throw }"); } #endregion # region "Data flow analysis tests" [Fact] public void DefiniteAssignmentOnAllControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int n = 3; int goo; // unassigned goo switch (n) { case 1: case 2: goo = n; break; case 3: default: goo = 0; break; } Console.Write(goo); // goo must be definitely assigned here return goo; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("SwitchTest.Main", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (int V_0, //n int V_1) //goo IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: sub IL_0005: ldc.i4.1 IL_0006: ble.un.s IL_000e IL_0008: ldloc.0 IL_0009: ldc.i4.3 IL_000a: beq.s IL_0012 IL_000c: br.s IL_0012 IL_000e: ldloc.0 IL_000f: stloc.1 IL_0010: br.s IL_0014 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: call ""void System.Console.Write(int)"" IL_001a: ldloc.1 IL_001b: ret }" ); } [Fact] public void ComplexControlFlow_DefiniteAssignmentOnAllControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int n = 3; int cost = 0; int goo; // unassigned goo switch (n) { case 1: cost = 1; goo = n; break; case 2: cost = 2; goto case 1; case 3: cost = 3; if(cost > n) { goo = n - 1; } else { goto case 2; } break; default: cost = 4; goo = n - 1; break; } if (goo != n) // goo must be reported as definitely assigned { Console.Write(goo); } else { --cost; } Console.Write(cost); // should output 0 return cost; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyIL("SwitchTest.Main", @"{ // Code size 78 (0x4e) .maxstack 2 .locals init (int V_0, //n int V_1, //cost int V_2) //goo IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldc.i4.1 IL_0006: sub IL_0007: switch ( IL_001a, IL_0020, IL_0024) IL_0018: br.s IL_0030 IL_001a: ldc.i4.1 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: stloc.2 IL_001e: br.s IL_0036 IL_0020: ldc.i4.2 IL_0021: stloc.1 IL_0022: br.s IL_001a IL_0024: ldc.i4.3 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldloc.0 IL_0028: ble.s IL_0020 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: sub IL_002d: stloc.2 IL_002e: br.s IL_0036 IL_0030: ldc.i4.4 IL_0031: stloc.1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: sub IL_0035: stloc.2 IL_0036: ldloc.2 IL_0037: ldloc.0 IL_0038: beq.s IL_0042 IL_003a: ldloc.2 IL_003b: call ""void System.Console.Write(int)"" IL_0040: br.s IL_0046 IL_0042: ldloc.1 IL_0043: ldc.i4.1 IL_0044: sub IL_0045: stloc.1 IL_0046: ldloc.1 IL_0047: call ""void System.Console.Write(int)"" IL_004c: ldloc.1 IL_004d: ret }" ); } [Fact] public void ComplexControlFlow_NoAssignmentOnlyOnUnreachableControlPaths() { var text = @"using System; class SwitchTest { public static int Main() { int goo; // unassigned goo switch (3) { case 1: mylabel: try { throw new System.ApplicationException(); } catch(Exception) { goo = 0; } break; case 2: goto mylabel; case 3: if (true) { goto case 2; } break; case 4: break; } Console.Write(goo); // goo should be definitely assigned here return goo; } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (27,17): warning CS0162: Unreachable code detected // break; Diagnostic(ErrorCode.WRN_UnreachableCode, "break"), // (29,17): warning CS0162: Unreachable code detected // break; Diagnostic(ErrorCode.WRN_UnreachableCode, "break")); compVerifier.VerifyIL("SwitchTest.Main", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) //goo IL_0000: nop .try { IL_0001: newobj ""System.ApplicationException..ctor()"" IL_0006: throw } catch System.Exception { IL_0007: pop IL_0008: ldc.i4.0 IL_0009: stloc.0 IL_000a: leave.s IL_000c } IL_000c: ldloc.0 IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldloc.0 IL_0013: ret }" ); } #endregion #region "Control flow analysis and warning tests" [Fact] public void CS0469_NoImplicitConversionWarning() { var text = @"using System; class A { static void Goo(DayOfWeek x) { switch (x) { case DayOfWeek.Monday: goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' } } static void Main() {} } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyDiagnostics( // (10,17): warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' // goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek' Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 1;").WithArguments("System.DayOfWeek")); compVerifier.VerifyIL("A.Goo", @" { // Code size 7 (0x7) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_0006 IL_0004: br.s IL_0004 IL_0006: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_01() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 2; switch (true) { case true: ret = 0; break; case false: // unreachable case label ret = 1; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (14,8): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret")); compVerifier.VerifyIL("Test.Main", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""void System.Console.Write(int)"" IL_000a: ldloc.0 IL_000b: ret } " ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_02() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 1; switch (true) { default: // unreachable default label ret = 1; break; case true: ret = 0; break; } Console.Write(ret); return(ret); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (11,17): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 17) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""void System.Console.Write(int)"" IL_000a: ldloc.0 IL_000b: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_03() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = M(); Console.Write(ret); return(ret); } public static int M() { switch (1) { case 1: return 0; } return 1; // unreachable code } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (19,5): warning CS0162: Unreachable code detected // return 1; // unreachable code Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(19, 5)); compVerifier.VerifyIL("Test.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }" ); } [Fact] public void CS0162_UnreachableCodeInSwitchCase_04() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; switch (1) // no matching case/default label { case 2: // unreachable code ret = 1; break; } Console.Write(ret); return(ret); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (11,9): warning CS0162: Unreachable code detected // ret = 1; Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 9) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0) //ret IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call ""void System.Console.Write(int)"" IL_0008: ldloc.0 IL_0009: ret }" ); } [Fact] public void CS1522_EmptySwitch() { var text = @"using System; public class Test { public static int Main(string [] args) { int ret = 0; switch (true) { } Console.Write(ret); return(0); } }"; var compVerifier = CompileAndVerify(text, expectedOutput: "0"); compVerifier.VerifyDiagnostics( // (7,23): warning CS1522: Empty switch block // switch (true) { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 23) ); compVerifier.VerifyIL("Test.Main", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ldc.i4.0 IL_0007: ret }" ); } [WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")] [Fact] public void DifferentStrategiesForDifferentSwitches() { var text = @" using System; public class Test { public static void Main(string [] args) { switch(args[0]) { case ""A"": Console.Write(1); break; } switch(args[1]) { case ""B"": Console.Write(2); break; case ""C"": Console.Write(3); break; case ""D"": Console.Write(4); break; case ""E"": Console.Write(5); break; case ""F"": Console.Write(6); break; case ""G"": Console.Write(7); break; case ""H"": Console.Write(8); break; case ""I"": Console.Write(9); break; case ""J"": Console.Write(10); break; } } }"; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE")); CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 326 (0x146) .maxstack 2 .locals init (string V_0, uint V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: ldstr ""A"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brfalse.s IL_0015 IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: ldarg.0 IL_0016: ldc.i4.1 IL_0017: ldelem.ref IL_0018: stloc.0 IL_0019: ldloc.0 IL_001a: call ""ComputeStringHash"" IL_001f: stloc.1 IL_0020: ldloc.1 IL_0021: ldc.i4 0xc30bf539 IL_0026: bgt.un.s IL_0055 IL_0028: ldloc.1 IL_0029: ldc.i4 0xc10bf213 IL_002e: bgt.un.s IL_0041 IL_0030: ldloc.1 IL_0031: ldc.i4 0xc00bf080 IL_0036: beq.s IL_00b1 IL_0038: ldloc.1 IL_0039: ldc.i4 0xc10bf213 IL_003e: beq.s IL_00a3 IL_0040: ret IL_0041: ldloc.1 IL_0042: ldc.i4 0xc20bf3a6 IL_0047: beq IL_00cd IL_004c: ldloc.1 IL_004d: ldc.i4 0xc30bf539 IL_0052: beq.s IL_00bf IL_0054: ret IL_0055: ldloc.1 IL_0056: ldc.i4 0xc70bfb85 IL_005b: bgt.un.s IL_006e IL_005d: ldloc.1 IL_005e: ldc.i4 0xc60bf9f2 IL_0063: beq.s IL_0095 IL_0065: ldloc.1 IL_0066: ldc.i4 0xc70bfb85 IL_006b: beq.s IL_0087 IL_006d: ret IL_006e: ldloc.1 IL_006f: ldc.i4 0xcc0c0364 IL_0074: beq.s IL_00e9 IL_0076: ldloc.1 IL_0077: ldc.i4 0xcd0c04f7 IL_007c: beq.s IL_00db IL_007e: ldloc.1 IL_007f: ldc.i4 0xcf0c081d IL_0084: beq.s IL_00f7 IL_0086: ret IL_0087: ldloc.0 IL_0088: ldstr ""B"" IL_008d: call ""bool string.op_Equality(string, string)"" IL_0092: brtrue.s IL_0105 IL_0094: ret IL_0095: ldloc.0 IL_0096: ldstr ""C"" IL_009b: call ""bool string.op_Equality(string, string)"" IL_00a0: brtrue.s IL_010c IL_00a2: ret IL_00a3: ldloc.0 IL_00a4: ldstr ""D"" IL_00a9: call ""bool string.op_Equality(string, string)"" IL_00ae: brtrue.s IL_0113 IL_00b0: ret IL_00b1: ldloc.0 IL_00b2: ldstr ""E"" IL_00b7: call ""bool string.op_Equality(string, string)"" IL_00bc: brtrue.s IL_011a IL_00be: ret IL_00bf: ldloc.0 IL_00c0: ldstr ""F"" IL_00c5: call ""bool string.op_Equality(string, string)"" IL_00ca: brtrue.s IL_0121 IL_00cc: ret IL_00cd: ldloc.0 IL_00ce: ldstr ""G"" IL_00d3: call ""bool string.op_Equality(string, string)"" IL_00d8: brtrue.s IL_0128 IL_00da: ret IL_00db: ldloc.0 IL_00dc: ldstr ""H"" IL_00e1: call ""bool string.op_Equality(string, string)"" IL_00e6: brtrue.s IL_012f IL_00e8: ret IL_00e9: ldloc.0 IL_00ea: ldstr ""I"" IL_00ef: call ""bool string.op_Equality(string, string)"" IL_00f4: brtrue.s IL_0136 IL_00f6: ret IL_00f7: ldloc.0 IL_00f8: ldstr ""J"" IL_00fd: call ""bool string.op_Equality(string, string)"" IL_0102: brtrue.s IL_013e IL_0104: ret IL_0105: ldc.i4.2 IL_0106: call ""void System.Console.Write(int)"" IL_010b: ret IL_010c: ldc.i4.3 IL_010d: call ""void System.Console.Write(int)"" IL_0112: ret IL_0113: ldc.i4.4 IL_0114: call ""void System.Console.Write(int)"" IL_0119: ret IL_011a: ldc.i4.5 IL_011b: call ""void System.Console.Write(int)"" IL_0120: ret IL_0121: ldc.i4.6 IL_0122: call ""void System.Console.Write(int)"" IL_0127: ret IL_0128: ldc.i4.7 IL_0129: call ""void System.Console.Write(int)"" IL_012e: ret IL_012f: ldc.i4.8 IL_0130: call ""void System.Console.Write(int)"" IL_0135: ret IL_0136: ldc.i4.s 9 IL_0138: call ""void System.Console.Write(int)"" IL_013d: ret IL_013e: ldc.i4.s 10 IL_0140: call ""void System.Console.Write(int)"" IL_0145: ret }"); } [WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")] [WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")] [Fact] public void LargeStringSwitchWithoutStringChars() { var text = @" using System; public class Test { public static void Main(string [] args) { switch(args[0]) { case ""A"": Console.Write(1); break; case ""B"": Console.Write(2); break; case ""C"": Console.Write(3); break; case ""D"": Console.Write(4); break; case ""E"": Console.Write(5); break; case ""F"": Console.Write(6); break; case ""G"": Console.Write(7); break; case ""H"": Console.Write(8); break; case ""I"": Console.Write(9); break; } } }"; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE")); // With special members available, we use a hashtable approach. CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 307 (0x133) .maxstack 2 .locals init (string V_0, uint V_1) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call ""ComputeStringHash"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: ldc.i4 0xc30bf539 IL_0011: bgt.un.s IL_0043 IL_0013: ldloc.1 IL_0014: ldc.i4 0xc10bf213 IL_0019: bgt.un.s IL_002f IL_001b: ldloc.1 IL_001c: ldc.i4 0xc00bf080 IL_0021: beq IL_00ad IL_0026: ldloc.1 IL_0027: ldc.i4 0xc10bf213 IL_002c: beq.s IL_009f IL_002e: ret IL_002f: ldloc.1 IL_0030: ldc.i4 0xc20bf3a6 IL_0035: beq IL_00c9 IL_003a: ldloc.1 IL_003b: ldc.i4 0xc30bf539 IL_0040: beq.s IL_00bb IL_0042: ret IL_0043: ldloc.1 IL_0044: ldc.i4 0xc60bf9f2 IL_0049: bgt.un.s IL_005c IL_004b: ldloc.1 IL_004c: ldc.i4 0xc40bf6cc IL_0051: beq.s IL_0075 IL_0053: ldloc.1 IL_0054: ldc.i4 0xc60bf9f2 IL_0059: beq.s IL_0091 IL_005b: ret IL_005c: ldloc.1 IL_005d: ldc.i4 0xc70bfb85 IL_0062: beq.s IL_0083 IL_0064: ldloc.1 IL_0065: ldc.i4 0xcc0c0364 IL_006a: beq.s IL_00e5 IL_006c: ldloc.1 IL_006d: ldc.i4 0xcd0c04f7 IL_0072: beq.s IL_00d7 IL_0074: ret IL_0075: ldloc.0 IL_0076: ldstr ""A"" IL_007b: call ""bool string.op_Equality(string, string)"" IL_0080: brtrue.s IL_00f3 IL_0082: ret IL_0083: ldloc.0 IL_0084: ldstr ""B"" IL_0089: call ""bool string.op_Equality(string, string)"" IL_008e: brtrue.s IL_00fa IL_0090: ret IL_0091: ldloc.0 IL_0092: ldstr ""C"" IL_0097: call ""bool string.op_Equality(string, string)"" IL_009c: brtrue.s IL_0101 IL_009e: ret IL_009f: ldloc.0 IL_00a0: ldstr ""D"" IL_00a5: call ""bool string.op_Equality(string, string)"" IL_00aa: brtrue.s IL_0108 IL_00ac: ret IL_00ad: ldloc.0 IL_00ae: ldstr ""E"" IL_00b3: call ""bool string.op_Equality(string, string)"" IL_00b8: brtrue.s IL_010f IL_00ba: ret IL_00bb: ldloc.0 IL_00bc: ldstr ""F"" IL_00c1: call ""bool string.op_Equality(string, string)"" IL_00c6: brtrue.s IL_0116 IL_00c8: ret IL_00c9: ldloc.0 IL_00ca: ldstr ""G"" IL_00cf: call ""bool string.op_Equality(string, string)"" IL_00d4: brtrue.s IL_011d IL_00d6: ret IL_00d7: ldloc.0 IL_00d8: ldstr ""H"" IL_00dd: call ""bool string.op_Equality(string, string)"" IL_00e2: brtrue.s IL_0124 IL_00e4: ret IL_00e5: ldloc.0 IL_00e6: ldstr ""I"" IL_00eb: call ""bool string.op_Equality(string, string)"" IL_00f0: brtrue.s IL_012b IL_00f2: ret IL_00f3: ldc.i4.1 IL_00f4: call ""void System.Console.Write(int)"" IL_00f9: ret IL_00fa: ldc.i4.2 IL_00fb: call ""void System.Console.Write(int)"" IL_0100: ret IL_0101: ldc.i4.3 IL_0102: call ""void System.Console.Write(int)"" IL_0107: ret IL_0108: ldc.i4.4 IL_0109: call ""void System.Console.Write(int)"" IL_010e: ret IL_010f: ldc.i4.5 IL_0110: call ""void System.Console.Write(int)"" IL_0115: ret IL_0116: ldc.i4.6 IL_0117: call ""void System.Console.Write(int)"" IL_011c: ret IL_011d: ldc.i4.7 IL_011e: call ""void System.Console.Write(int)"" IL_0123: ret IL_0124: ldc.i4.8 IL_0125: call ""void System.Console.Write(int)"" IL_012a: ret IL_012b: ldc.i4.s 9 IL_012d: call ""void System.Console.Write(int)"" IL_0132: ret }"); comp = CreateCompilation(text); comp.MakeMemberMissing(SpecialMember.System_String__Chars); // Can't use the hash version when String.Chars is unavailable. CompileAndVerify(comp).VerifyIL("Test.Main", @" { // Code size 186 (0xba) .maxstack 2 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.ref IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldstr ""A"" IL_000a: call ""bool string.op_Equality(string, string)"" IL_000f: brtrue.s IL_007a IL_0011: ldloc.0 IL_0012: ldstr ""B"" IL_0017: call ""bool string.op_Equality(string, string)"" IL_001c: brtrue.s IL_0081 IL_001e: ldloc.0 IL_001f: ldstr ""C"" IL_0024: call ""bool string.op_Equality(string, string)"" IL_0029: brtrue.s IL_0088 IL_002b: ldloc.0 IL_002c: ldstr ""D"" IL_0031: call ""bool string.op_Equality(string, string)"" IL_0036: brtrue.s IL_008f IL_0038: ldloc.0 IL_0039: ldstr ""E"" IL_003e: call ""bool string.op_Equality(string, string)"" IL_0043: brtrue.s IL_0096 IL_0045: ldloc.0 IL_0046: ldstr ""F"" IL_004b: call ""bool string.op_Equality(string, string)"" IL_0050: brtrue.s IL_009d IL_0052: ldloc.0 IL_0053: ldstr ""G"" IL_0058: call ""bool string.op_Equality(string, string)"" IL_005d: brtrue.s IL_00a4 IL_005f: ldloc.0 IL_0060: ldstr ""H"" IL_0065: call ""bool string.op_Equality(string, string)"" IL_006a: brtrue.s IL_00ab IL_006c: ldloc.0 IL_006d: ldstr ""I"" IL_0072: call ""bool string.op_Equality(string, string)"" IL_0077: brtrue.s IL_00b2 IL_0079: ret IL_007a: ldc.i4.1 IL_007b: call ""void System.Console.Write(int)"" IL_0080: ret IL_0081: ldc.i4.2 IL_0082: call ""void System.Console.Write(int)"" IL_0087: ret IL_0088: ldc.i4.3 IL_0089: call ""void System.Console.Write(int)"" IL_008e: ret IL_008f: ldc.i4.4 IL_0090: call ""void System.Console.Write(int)"" IL_0095: ret IL_0096: ldc.i4.5 IL_0097: call ""void System.Console.Write(int)"" IL_009c: ret IL_009d: ldc.i4.6 IL_009e: call ""void System.Console.Write(int)"" IL_00a3: ret IL_00a4: ldc.i4.7 IL_00a5: call ""void System.Console.Write(int)"" IL_00aa: ret IL_00ab: ldc.i4.8 IL_00ac: call ""void System.Console.Write(int)"" IL_00b1: ret IL_00b2: ldc.i4.s 9 IL_00b4: call ""void System.Console.Write(int)"" IL_00b9: ret }"); } [WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")] [Fact] public void Regress947580() { var text = @" using System; class Program { static string boo(int i) { switch (i) { case 42: var x = ""goo""; if (x != ""bar"") break; return x; } return null; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //x IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_001a IL_0005: ldstr ""goo"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""bar"" IL_0011: call ""bool string.op_Inequality(string, string)"" IL_0016: brtrue.s IL_001a IL_0018: ldloc.0 IL_0019: ret IL_001a: ldnull IL_001b: ret }" ); } [WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")] [Fact] public void Regress947580a() { var text = @" using System; class Program { static string boo(int i) { switch (i) { case 42: var x = ""goo""; if (x != ""bar"") break; break; } return null; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_0015 IL_0005: ldstr ""goo"" IL_000a: ldstr ""bar"" IL_000f: call ""bool string.op_Inequality(string, string)"" IL_0014: pop IL_0015: ldnull IL_0016: ret }" ); } [WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")] [Fact] public void Regress1035228() { var text = @" using System; class Program { static bool boo(int i) { var ii = i; switch (++ii) { case 42: var x = ""goo""; if (x != ""bar"") { return false; } break; } return true; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: add IL_0003: ldc.i4.s 42 IL_0005: bne.un.s IL_001a IL_0007: ldstr ""goo"" IL_000c: ldstr ""bar"" IL_0011: call ""bool string.op_Inequality(string, string)"" IL_0016: brfalse.s IL_001a IL_0018: ldc.i4.0 IL_0019: ret IL_001a: ldc.i4.1 IL_001b: ret }" ); } [WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")] [Fact] public void Regress1035228a() { var text = @" using System; class Program { static bool boo(int i) { var ii = i; switch (ii++) { case 42: var x = ""goo""; if (x != ""bar"") { return false; } break; } return true; } static void Main() { boo(42); } } "; var compVerifier = CompileAndVerify(text, expectedOutput: ""); compVerifier.VerifyIL("Program.boo", @"{ // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: bne.un.s IL_0018 IL_0005: ldstr ""goo"" IL_000a: ldstr ""bar"" IL_000f: call ""bool string.op_Inequality(string, string)"" IL_0014: brfalse.s IL_0018 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldc.i4.1 IL_0019: ret }" ); } [WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")] [Fact] public void Regress4701() { var text = @" using System; namespace ConsoleApplication1 { class Program { private void SwtchTest() { int? i; i = 1; switch (i) { case null: Console.WriteLine(""In Null case""); i = 1; break; default: Console.WriteLine(""In DEFAULT case""); i = i + 2; break; } } static void Main(string[] args) { var p = new Program(); p.SwtchTest(); } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case"); compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest", @" { // Code size 84 (0x54) .maxstack 2 .locals init (int? V_0, //i int? V_1, int? V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""int?..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""bool int?.HasValue.get"" IL_000f: brtrue.s IL_0024 IL_0011: ldstr ""In Null case"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.1 IL_001e: call ""int?..ctor(int)"" IL_0023: ret IL_0024: ldstr ""In DEFAULT case"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ldloc.0 IL_002f: stloc.1 IL_0030: ldloca.s V_1 IL_0032: call ""bool int?.HasValue.get"" IL_0037: brtrue.s IL_0044 IL_0039: ldloca.s V_2 IL_003b: initobj ""int?"" IL_0041: ldloc.2 IL_0042: br.s IL_0052 IL_0044: ldloca.s V_1 IL_0046: call ""int int?.GetValueOrDefault()"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: newobj ""int?..ctor(int)"" IL_0052: stloc.0 IL_0053: ret }" ); } [WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")] [Fact] public void Regress4701a() { var text = @" using System; namespace ConsoleApplication1 { class Program { private void SwtchTest() { string i = null; i = ""1""; switch (i) { case null: Console.WriteLine(""In Null case""); break; default: Console.WriteLine(""In DEFAULT case""); break; } } static void Main(string[] args) { var p = new Program(); p.SwtchTest(); } } } "; var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case"); compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldstr ""1"" IL_0005: brtrue.s IL_0012 IL_0007: ldstr ""In Null case"" IL_000c: call ""void System.Console.WriteLine(string)"" IL_0011: ret IL_0012: ldstr ""In DEFAULT case"" IL_0017: call ""void System.Console.WriteLine(string)"" IL_001c: ret }" ); } #endregion #region regression tests [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_01() { var source = @"using System; public class Program { public static void Main() { switch (StringSplitOptions.RemoveEmptyEntries) { case object o: Console.WriteLine(o); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""System.StringSplitOptions"" IL_0006: call ""void System.Console.WriteLine(object)"" IL_000b: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 26 (0x1a) .maxstack 1 .locals init (object V_0, //o System.StringSplitOptions V_1, System.StringSplitOptions V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldc.i4.1 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""System.StringSplitOptions"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: call ""void System.Console.WriteLine(object)"" IL_0016: nop IL_0017: br.s IL_0019 IL_0019: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void ExplicitNullablePatternSwitch_02() { var source = @"using System; public class Program { public static void Main() { M(null); M(1); } public static void M(int? x) { switch (x) { case int i: // explicit nullable conversion Console.Write(i); break; case null: Console.Write(""null""); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "null1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 33 (0x21) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brfalse.s IL_0016 IL_0009: ldarga.s V_0 IL_000b: call ""int int?.GetValueOrDefault()"" IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldstr ""null"" IL_001b: call ""void System.Console.Write(string)"" IL_0020: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "null1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (int V_0, //i int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloca.s V_1 IL_0007: call ""bool int?.HasValue.get"" IL_000c: brfalse.s IL_0023 IL_000e: ldloca.s V_1 IL_0010: call ""int int?.GetValueOrDefault()"" IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: br.s IL_001a IL_001a: ldloc.0 IL_001b: call ""void System.Console.Write(int)"" IL_0020: nop IL_0021: br.s IL_0030 IL_0023: ldstr ""null"" IL_0028: call ""void System.Console.Write(string)"" IL_002d: nop IL_002e: br.s IL_0030 IL_0030: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_04() { var source = @"using System; public class Program { public static void Main() { M(1); } public static void M(int x) { switch (x) { case System.IComparable i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""int"" IL_0006: call ""void System.Console.Write(object)"" IL_000b: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 26 (0x1a) .maxstack 1 .locals init (System.IComparable V_0, //i int V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""int"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: call ""void System.Console.Write(object)"" IL_0016: nop IL_0017: br.s IL_0019 IL_0019: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternSwitch_05() { var source = @"using System; public class Program { public static void Main() { M(1); M(null); } public static void M(int? x) { switch (x) { case System.IComparable i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 17 (0x11) .maxstack 1 .locals init (System.IComparable V_0) //i IL_0000: ldarg.0 IL_0001: box ""int?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: call ""void System.Console.Write(object)"" IL_0010: ret } " ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (System.IComparable V_0, //i int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""int?"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_001c IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: call ""void System.Console.Write(object)"" IL_0019: nop IL_001a: br.s IL_001c IL_001c: ret } " ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_06() { var source = @"using System; public class Program { public static void Main() { M(1); M(null); M(nameof(Main)); } public static void M(object x) { switch (x) { case int i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""int"" IL_0006: brfalse.s IL_0013 IL_0008: ldarg.0 IL_0009: unbox.any ""int"" IL_000e: call ""void System.Console.Write(int)"" IL_0013: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M", @"{ // Code size 34 (0x22) .maxstack 1 .locals init (int V_0, //i object V_1, object V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0021 IL_000d: ldloc.1 IL_000e: unbox.any ""int"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: call ""void System.Console.Write(int)"" IL_001e: nop IL_001f: br.s IL_0021 IL_0021: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_07() { var source = @"using System; public class Program { public static void Main() { M<int>(1); M<int>(null); M<int>(10.5); } public static void M<T>(object x) { // when T is not known to be a reference type, there is an unboxing conversion from // the effective base class C of T to T and from any base class of C to T. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0018 IL_0008: ldarg.0 IL_0009: unbox.any ""T"" IL_000e: box ""T"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 39 (0x27) .maxstack 1 .locals init (T V_0, //i object V_1, object V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0026 IL_000d: ldloc.1 IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: box ""T"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: nop IL_0024: br.s IL_0026 IL_0026: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnboxInPatternSwitch_08() { var source = @"using System; public class Program { public static void Main() { M<int>(1); M<int>(null); M<int>(10.5); } public static void M<T>(IComparable x) { // when T is not known to be a reference type, there is an unboxing conversion from // any interface type to T. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0018 IL_0008: ldarg.0 IL_0009: unbox.any ""T"" IL_000e: box ""T"" IL_0013: call ""void System.Console.Write(object)"" IL_0018: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T>", @"{ // Code size 39 (0x27) .maxstack 1 .locals init (T V_0, //i System.IComparable V_1, System.IComparable V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0026 IL_000d: ldloc.1 IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: box ""T"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: nop IL_0024: br.s IL_0026 IL_0026: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void UnoxInPatternSwitch_09() { var source = @"using System; public class Program { public static void Main() { M<int, object>(1); M<int, object>(null); M<int, object>(10.5); } public static void M<T, U>(U x) where T : U { // when T is not known to be a reference type, there is an unboxing conversion from // a type parameter U to T, provided T depends on U. switch (x) { case T i: Console.Write(i); break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T, U>", @"{ // Code size 35 (0x23) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""U"" IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0022 IL_000d: ldarg.0 IL_000e: box ""U"" IL_0013: unbox.any ""T"" IL_0018: box ""T"" IL_001d: call ""void System.Console.Write(object)"" IL_0022: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "1"); compVerifier.VerifyIL("Program.M<T, U>", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (T V_0, //i U V_1, U V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""U"" IL_000b: isinst ""T"" IL_0010: brfalse.s IL_0030 IL_0012: ldloc.1 IL_0013: box ""U"" IL_0018: unbox.any ""T"" IL_001d: stloc.0 IL_001e: br.s IL_0020 IL_0020: br.s IL_0022 IL_0022: ldloc.0 IL_0023: box ""T"" IL_0028: call ""void System.Console.Write(object)"" IL_002d: nop IL_002e: br.s IL_0030 IL_0030: ret }" ); } [Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")] public void BoxInPatternIf_02() { var source = @"using System; public class Program { public static void Main() { if (StringSplitOptions.RemoveEmptyEntries is object o) { Console.WriteLine(o); } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 14 (0xe) .maxstack 1 .locals init (object V_0) //o IL_0000: ldc.i4.1 IL_0001: box ""System.StringSplitOptions"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "RemoveEmptyEntries"); compVerifier.VerifyIL("Program.Main", @"{ // Code size 23 (0x17) .maxstack 1 .locals init (object V_0, //o bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""System.StringSplitOptions"" IL_0007: stloc.0 IL_0008: ldc.i4.1 IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: brfalse.s IL_0016 IL_000d: nop IL_000e: ldloc.0 IL_000f: call ""void System.Console.WriteLine(object)"" IL_0014: nop IL_0015: nop IL_0016: ret }" ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_01() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<int>(2)); Console.Write(M2<int>(3)); Console.Write(M1<int>(1.1)); Console.Write(M2<int>(1.1)); } public static T M1<T>(ValueType o) { return o is T t ? t : default(T); } public static T M2<T>(ValueType o) { switch (o) { case T t: return t; default: return default(T); } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(19, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 34 (0x22) .maxstack 1 .locals init (T V_0, //t T V_1) IL_0000: ldarg.0 IL_0001: isinst ""T"" IL_0006: brfalse.s IL_0016 IL_0008: ldarg.0 IL_0009: isinst ""T"" IL_000e: unbox.any ""T"" IL_0013: stloc.0 IL_0014: br.s IL_0020 IL_0016: ldloca.s V_1 IL_0018: initobj ""T"" IL_001e: ldloc.1 IL_001f: ret IL_0020: ldloc.0 IL_0021: ret }" ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 40 (0x28) .maxstack 1 .locals init (T V_0, //t T V_1, T V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""T"" IL_0007: brfalse.s IL_0017 IL_0009: ldarg.0 IL_000a: isinst ""T"" IL_000f: unbox.any ""T"" IL_0014: stloc.0 IL_0015: br.s IL_0022 IL_0017: ldloca.s V_1 IL_0019: initobj ""T"" IL_001f: ldloc.1 IL_0020: br.s IL_0023 IL_0022: ldloc.0 IL_0023: stloc.2 IL_0024: br.s IL_0026 IL_0026: ldloc.2 IL_0027: ret }" ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 48 (0x30) .maxstack 1 .locals init (T V_0, //t System.ValueType V_1, System.ValueType V_2, T V_3, T V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""T"" IL_000b: brfalse.s IL_0021 IL_000d: ldloc.1 IL_000e: isinst ""T"" IL_0013: unbox.any ""T"" IL_0018: stloc.0 IL_0019: br.s IL_001b IL_001b: br.s IL_001d IL_001d: ldloc.0 IL_001e: stloc.3 IL_001f: br.s IL_002e IL_0021: ldloca.s V_4 IL_0023: initobj ""T"" IL_0029: ldloc.s V_4 IL_002b: stloc.3 IL_002c: br.s IL_002e IL_002e: ldloc.3 IL_002f: ret }" ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_02() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1(2)); Console.Write(M2(3)); Console.Write(M1(1.1)); Console.Write(M2(1.1)); } public static int M1<T>(T o) { return o is int t ? t : default(int); } public static int M2<T>(T o) { switch (o) { case int t: return t; default: return default(int); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater. // return o is int t ? t : default(int); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater. // case int t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(19, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 36 (0x24) .maxstack 1 .locals init (int V_0) //t IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0020 IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: stloc.0 IL_001e: br.s IL_0022 IL_0020: ldc.i4.0 IL_0021: ret IL_0022: ldloc.0 IL_0023: ret } " ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 32 (0x20) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: isinst ""int"" IL_000b: brfalse.s IL_001e IL_000d: ldarg.0 IL_000e: box ""T"" IL_0013: isinst ""int"" IL_0018: unbox.any ""int"" IL_001d: ret IL_001e: ldc.i4.0 IL_001f: ret } " ); compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "2300"); compVerifier.VerifyIL("Program.M1<T>", @"{ // Code size 42 (0x2a) .maxstack 1 .locals init (int V_0, //t int V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: isinst ""int"" IL_000c: brfalse.s IL_0021 IL_000e: ldarg.0 IL_000f: box ""T"" IL_0014: isinst ""int"" IL_0019: unbox.any ""int"" IL_001e: stloc.0 IL_001f: br.s IL_0024 IL_0021: ldc.i4.0 IL_0022: br.s IL_0025 IL_0024: ldloc.0 IL_0025: stloc.1 IL_0026: br.s IL_0028 IL_0028: ldloc.1 IL_0029: ret } " ); compVerifier.VerifyIL("Program.M2<T>", @"{ // Code size 49 (0x31) .maxstack 1 .locals init (int V_0, //t T V_1, T V_2, int V_3) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: box ""T"" IL_000b: isinst ""int"" IL_0010: brfalse.s IL_002b IL_0012: ldloc.1 IL_0013: box ""T"" IL_0018: isinst ""int"" IL_001d: unbox.any ""int"" IL_0022: stloc.0 IL_0023: br.s IL_0025 IL_0025: br.s IL_0027 IL_0027: ldloc.0 IL_0028: stloc.3 IL_0029: br.s IL_002f IL_002b: ldc.i4.0 IL_002c: stloc.3 IL_002d: br.s IL_002f IL_002f: ldloc.3 IL_0030: ret } " ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_03() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<int>(2)); Console.Write(M2<int>(3)); Console.Write(M1<int>(1.1)); Console.Write(M2<int>(1.1)); } public static T M1<T>(ValueType o) where T : struct { return o is T t ? t : default(T); } public static T M2<T>(ValueType o) where T : struct { switch (o) { case T t: return t; default: return default(T); } } } "; var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: "2300"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_04() { var source = @"using System; class Program { public static void Main(string[] args) { var x = new X(); Console.Write(M1<B>(new A()) ?? x); Console.Write(M2<B>(new A()) ?? x); Console.Write(M1<B>(new B()) ?? x); Console.Write(M2<B>(new B()) ?? x); } public static T M1<T>(A o) where T : class { return o is T t ? t : default(T); } public static T M2<T>(A o) where T : class { switch (o) { case T t: return t; default: return default(T); } } } class A { } class B : A { } class X : B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21), // (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "XXBB"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_05() { var source = @"using System; class Program { public static void Main(string[] args) { var x = new X(); Console.Write(M1<B>(new A()) ?? x); Console.Write(M2<B>(new A()) ?? x); Console.Write(M1<B>(new B()) ?? x); Console.Write(M2<B>(new B()) ?? x); } public static T M1<T>(A o) where T : I1 { return o is T t ? t : default(T); } public static T M2<T>(A o) where T : I1 { switch (o) { case T t: return t; default: return default(T); } } } interface I1 { } class A : I1 { } class B : A { } class X : B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t ? t : default(T); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21), // (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18) ); var compVerifier = CompileAndVerify(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1, expectedOutput: "XXBB"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_06() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<B>(new A())); Console.Write(M2<B>(new A())); Console.Write(M1<A>(new A())); Console.Write(M2<A>(new A())); } public static bool M1<T>(A o) where T : I1 { return o is T t; } public static bool M2<T>(A o) where T : I1 { switch (o) { case T t: return true; default: return false; } } } interface I1 { } struct A : I1 { } struct B : I1 { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18) ); var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "FalseFalseTrueTrue"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestMatchWithTypeParameter_07() { var source = @"using System; class Program { public static void Main(string[] args) { Console.Write(M1<B>(new A())); Console.Write(M2<B>(new A())); Console.Write(M1<A>(new A())); Console.Write(M2<A>(new A())); } public static bool M1<T>(A o) where T : new() { return o is T t; } public static bool M2<T>(A o) where T : new() { switch (o) { case T t: return true; default: return false; } } } struct A { } struct B { } "; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // return o is T t; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21), // (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T t: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18) ); var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.Regular7_1) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "FalseFalseTrueTrue"); compVerifier.VerifyDiagnostics(); } [Fact] [WorkItem(16195, "https://github.com/dotnet/roslyn/issues/31269")] public void TestIgnoreDynamicVsObjectAndTupleElementNames_01() { var source = @"public class Generic<T> { public enum Color { Red=1, Blue=2 } } class Program { public static void Main(string[] args) { } public static void M2(object o) { switch (o) { case Generic<long>.Color c: case Generic<object>.Color.Red: case Generic<(int x, int y)>.Color.Blue: case Generic<string>.Color.Red: case Generic<dynamic>.Color.Red: // error: duplicate case case Generic<(int z, int w)>.Color.Blue: // error: duplicate case case Generic<(int z, long w)>.Color.Blue: default: break; } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case Generic<dynamic>.Color.Red: // error: duplicate case Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<dynamic>.Color.Red:").WithArguments("1").WithLocation(18, 13), // (19,13): error CS0152: The switch statement contains multiple cases with the label value '2' // case Generic<(int z, int w)>.Color.Blue: // error: duplicate case Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<(int z, int w)>.Color.Blue:").WithArguments("2").WithLocation(19, 13) ); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TestIgnoreDynamicVsObjectAndTupleElementNames_02() { var source = @"using System; public class Generic<T> { public enum Color { X0, X1, X2, Green, Blue, Red } } class Program { public static void Main(string[] args) { Console.WriteLine(M1<Generic<int>.Color>(Generic<long>.Color.Red)); // False Console.WriteLine(M1<Generic<string>.Color>(Generic<object>.Color.Red)); // False Console.WriteLine(M1<Generic<(int x, int y)>.Color>(Generic<(int z, int w)>.Color.Red)); // True Console.WriteLine(M1<Generic<object>.Color>(Generic<dynamic>.Color.Blue)); // True Console.WriteLine(M2(Generic<long>.Color.Red)); // Generic<long>.Color.Red Console.WriteLine(M2(Generic<object>.Color.Blue)); // Generic<dynamic>.Color.Blue Console.WriteLine(M2(Generic<int>.Color.Red)); // None Console.WriteLine(M2(Generic<dynamic>.Color.Red)); // Generic<object>.Color.Red } public static bool M1<T>(object o) { return o is T t; } public static string M2(object o) { switch (o) { case Generic<long>.Color c: return ""Generic<long>.Color."" + c; case Generic<object>.Color.Red: return ""Generic<object>.Color.Red""; case Generic<dynamic>.Color.Blue: return ""Generic<dynamic>.Color.Blue""; default: return ""None""; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: @"False False True True Generic<long>.Color.Red Generic<dynamic>.Color.Blue None Generic<object>.Color.Red"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (Generic<long>.Color V_0, //c object V_1, Generic<object>.Color V_2, object V_3, string V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: isinst ""Generic<long>.Color"" IL_000b: brfalse.s IL_0016 IL_000d: ldloc.1 IL_000e: unbox.any ""Generic<long>.Color"" IL_0013: stloc.0 IL_0014: br.s IL_0031 IL_0016: ldloc.1 IL_0017: isinst ""Generic<object>.Color"" IL_001c: brfalse.s IL_0060 IL_001e: ldloc.1 IL_001f: unbox.any ""Generic<object>.Color"" IL_0024: stloc.2 IL_0025: ldloc.2 IL_0026: ldc.i4.4 IL_0027: beq.s IL_0057 IL_0029: br.s IL_002b IL_002b: ldloc.2 IL_002c: ldc.i4.5 IL_002d: beq.s IL_004e IL_002f: br.s IL_0060 IL_0031: br.s IL_0033 IL_0033: ldstr ""Generic<long>.Color."" IL_0038: ldloca.s V_0 IL_003a: constrained. ""Generic<long>.Color"" IL_0040: callvirt ""string object.ToString()"" IL_0045: call ""string string.Concat(string, string)"" IL_004a: stloc.s V_4 IL_004c: br.s IL_0069 IL_004e: ldstr ""Generic<object>.Color.Red"" IL_0053: stloc.s V_4 IL_0055: br.s IL_0069 IL_0057: ldstr ""Generic<dynamic>.Color.Blue"" IL_005c: stloc.s V_4 IL_005e: br.s IL_0069 IL_0060: ldstr ""None"" IL_0065: stloc.s V_4 IL_0067: br.s IL_0069 IL_0069: ldloc.s V_4 IL_006b: ret } " ); } [Fact, WorkItem(16129, "https://github.com/dotnet/roslyn/issues/16129")] public void ExactPatternMatch() { var source = @"using System; class C { static void Main() { if (TrySomething() is ValueTuple<string, bool> v && v.Item2) { System.Console.Write(v.Item1 == null); } } static (string Value, bool Success) TrySomething() { return (null, true); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: @"True"); compVerifier.VerifyIL("C.Main", @"{ // Code size 29 (0x1d) .maxstack 2 .locals init (System.ValueTuple<string, bool> V_0) //v IL_0000: call ""System.ValueTuple<string, bool> C.TrySomething()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_000c: brfalse.s IL_001c IL_000e: ldloc.0 IL_000f: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_0014: ldnull IL_0015: ceq IL_0017: call ""void System.Console.Write(bool)"" IL_001c: ret }" ); } [WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ShareLikeKindedTemps_01() { var source = @"using System; public class Program { public static void Main() { } static bool b = false; public static void M(object o) { switch (o) { case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; case int i when b: break; case var _ when b: break; } } }"; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication), expectedOutput: ""); compVerifier.VerifyIL("Program.M", @" { // Code size 120 (0x78) .maxstack 2 .locals init (int V_0, int V_1, //i object V_2) IL_0000: ldarg.0 IL_0001: stloc.2 IL_0002: ldloc.2 IL_0003: isinst ""int"" IL_0008: brfalse.s IL_001c IL_000a: ldloc.2 IL_000b: unbox.any ""int"" IL_0010: stloc.1 IL_0011: ldsfld ""bool Program.b"" IL_0016: brtrue.s IL_0077 IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: br.s IL_001e IL_001c: ldc.i4.7 IL_001d: stloc.0 IL_001e: ldsfld ""bool Program.b"" IL_0023: brtrue.s IL_0077 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: beq.s IL_002e IL_0029: ldloc.0 IL_002a: ldc.i4.7 IL_002b: beq.s IL_0039 IL_002d: ret IL_002e: ldsfld ""bool Program.b"" IL_0033: brtrue.s IL_0077 IL_0035: ldc.i4.3 IL_0036: stloc.0 IL_0037: br.s IL_003b IL_0039: ldc.i4.8 IL_003a: stloc.0 IL_003b: ldsfld ""bool Program.b"" IL_0040: brtrue.s IL_0077 IL_0042: ldloc.0 IL_0043: ldc.i4.3 IL_0044: beq.s IL_004b IL_0046: ldloc.0 IL_0047: ldc.i4.8 IL_0048: beq.s IL_0056 IL_004a: ret IL_004b: ldsfld ""bool Program.b"" IL_0050: brtrue.s IL_0077 IL_0052: ldc.i4.5 IL_0053: stloc.0 IL_0054: br.s IL_0059 IL_0056: ldc.i4.s 9 IL_0058: stloc.0 IL_0059: ldsfld ""bool Program.b"" IL_005e: brtrue.s IL_0077 IL_0060: ldloc.0 IL_0061: ldc.i4.5 IL_0062: beq.s IL_006a IL_0064: ldloc.0 IL_0065: ldc.i4.s 9 IL_0067: beq.s IL_0071 IL_0069: ret IL_006a: ldsfld ""bool Program.b"" IL_006f: brtrue.s IL_0077 IL_0071: ldsfld ""bool Program.b"" IL_0076: pop IL_0077: ret }" ); compVerifier = CompileAndVerify(source, expectedOutput: "", symbolValidator: validator, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication).WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("Program"); Assert.Null(type.GetMember(".cctor")); } compVerifier.VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source, expectedIL: @"{ // Code size 194 (0xc2) .maxstack 2 .locals init (int V_0, int V_1, //i int V_2, //i int V_3, //i int V_4, //i object V_5, object V_6) // sequence point: { IL_0000: nop // sequence point: switch (o) IL_0001: ldarg.0 IL_0002: stloc.s V_6 // sequence point: <hidden> IL_0004: ldloc.s V_6 IL_0006: stloc.s V_5 // sequence point: <hidden> IL_0008: ldloc.s V_5 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_002d IL_0011: ldloc.s V_5 IL_0013: unbox.any ""int"" IL_0018: stloc.1 // sequence point: <hidden> IL_0019: br.s IL_001b // sequence point: when b IL_001b: ldsfld ""bool Program.b"" IL_0020: brtrue.s IL_0024 // sequence point: <hidden> IL_0022: br.s IL_0029 // sequence point: break; IL_0024: br IL_00c1 // sequence point: <hidden> IL_0029: ldc.i4.1 IL_002a: stloc.0 IL_002b: br.s IL_0031 IL_002d: ldc.i4.7 IL_002e: stloc.0 IL_002f: br.s IL_0031 // sequence point: when b IL_0031: ldsfld ""bool Program.b"" IL_0036: brtrue.s IL_0048 // sequence point: <hidden> IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: beq.s IL_0044 IL_003c: br.s IL_003e IL_003e: ldloc.0 IL_003f: ldc.i4.7 IL_0040: beq.s IL_0046 IL_0042: br.s IL_0048 IL_0044: br.s IL_004a IL_0046: br.s IL_005b // sequence point: break; IL_0048: br.s IL_00c1 // sequence point: <hidden> IL_004a: ldloc.1 IL_004b: stloc.2 // sequence point: when b IL_004c: ldsfld ""bool Program.b"" IL_0051: brtrue.s IL_0055 // sequence point: <hidden> IL_0053: br.s IL_0057 // sequence point: break; IL_0055: br.s IL_00c1 // sequence point: <hidden> IL_0057: ldc.i4.3 IL_0058: stloc.0 IL_0059: br.s IL_005f IL_005b: ldc.i4.8 IL_005c: stloc.0 IL_005d: br.s IL_005f // sequence point: when b IL_005f: ldsfld ""bool Program.b"" IL_0064: brtrue.s IL_0076 // sequence point: <hidden> IL_0066: ldloc.0 IL_0067: ldc.i4.3 IL_0068: beq.s IL_0072 IL_006a: br.s IL_006c IL_006c: ldloc.0 IL_006d: ldc.i4.8 IL_006e: beq.s IL_0074 IL_0070: br.s IL_0076 IL_0072: br.s IL_0078 IL_0074: br.s IL_0089 // sequence point: break; IL_0076: br.s IL_00c1 // sequence point: <hidden> IL_0078: ldloc.1 IL_0079: stloc.3 // sequence point: when b IL_007a: ldsfld ""bool Program.b"" IL_007f: brtrue.s IL_0083 // sequence point: <hidden> IL_0081: br.s IL_0085 // sequence point: break; IL_0083: br.s IL_00c1 // sequence point: <hidden> IL_0085: ldc.i4.5 IL_0086: stloc.0 IL_0087: br.s IL_008e IL_0089: ldc.i4.s 9 IL_008b: stloc.0 IL_008c: br.s IL_008e // sequence point: when b IL_008e: ldsfld ""bool Program.b"" IL_0093: brtrue.s IL_00a6 // sequence point: <hidden> IL_0095: ldloc.0 IL_0096: ldc.i4.5 IL_0097: beq.s IL_00a2 IL_0099: br.s IL_009b IL_009b: ldloc.0 IL_009c: ldc.i4.s 9 IL_009e: beq.s IL_00a4 IL_00a0: br.s IL_00a6 IL_00a2: br.s IL_00a8 IL_00a4: br.s IL_00b6 // sequence point: break; IL_00a6: br.s IL_00c1 // sequence point: <hidden> IL_00a8: ldloc.1 IL_00a9: stloc.s V_4 // sequence point: when b IL_00ab: ldsfld ""bool Program.b"" IL_00b0: brtrue.s IL_00b4 // sequence point: <hidden> IL_00b2: br.s IL_00b6 // sequence point: break; IL_00b4: br.s IL_00c1 // sequence point: when b IL_00b6: ldsfld ""bool Program.b"" IL_00bb: brtrue.s IL_00bf // sequence point: <hidden> IL_00bd: br.s IL_00c1 // sequence point: break; IL_00bf: br.s IL_00c1 // sequence point: } IL_00c1: ret }" ); compVerifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""Program"" methodName=""Main"" /> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method containingType=""Program"" name=""M"" parameterNames=""o""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""0"" offset=""55"" /> <slot kind=""0"" offset=""133"" /> <slot kind=""0"" offset=""211"" /> <slot kind=""0"" offset=""289"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""38"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""13"" startColumn=""24"" endLine=""13"" endColumn=""30"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""32"" endLine=""13"" endColumn=""38"" document=""1"" /> <entry offset=""0x4a"" hidden=""true"" document=""1"" /> <entry offset=""0x4c"" startLine=""14"" startColumn=""24"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x53"" hidden=""true"" document=""1"" /> <entry offset=""0x55"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""38"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x5f"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""30"" document=""1"" /> <entry offset=""0x66"" hidden=""true"" document=""1"" /> <entry offset=""0x76"" startLine=""15"" startColumn=""32"" endLine=""15"" endColumn=""38"" document=""1"" /> <entry offset=""0x78"" hidden=""true"" document=""1"" /> <entry offset=""0x7a"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x81"" hidden=""true"" document=""1"" /> <entry offset=""0x83"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""38"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""17"" startColumn=""24"" endLine=""17"" endColumn=""30"" document=""1"" /> <entry offset=""0x95"" hidden=""true"" document=""1"" /> <entry offset=""0xa6"" startLine=""17"" startColumn=""32"" endLine=""17"" endColumn=""38"" document=""1"" /> <entry offset=""0xa8"" hidden=""true"" document=""1"" /> <entry offset=""0xab"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""30"" document=""1"" /> <entry offset=""0xb2"" hidden=""true"" document=""1"" /> <entry offset=""0xb4"" startLine=""18"" startColumn=""32"" endLine=""18"" endColumn=""38"" document=""1"" /> <entry offset=""0xb6"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""30"" document=""1"" /> <entry offset=""0xbd"" hidden=""true"" document=""1"" /> <entry offset=""0xbf"" startLine=""19"" startColumn=""32"" endLine=""19"" endColumn=""38"" document=""1"" /> <entry offset=""0xc1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc2""> <scope startOffset=""0x1b"" endOffset=""0x29""> <local name=""i"" il_index=""1"" il_start=""0x1b"" il_end=""0x29"" attributes=""0"" /> </scope> <scope startOffset=""0x4a"" endOffset=""0x57""> <local name=""i"" il_index=""2"" il_start=""0x4a"" il_end=""0x57"" attributes=""0"" /> </scope> <scope startOffset=""0x78"" endOffset=""0x85""> <local name=""i"" il_index=""3"" il_start=""0x78"" il_end=""0x85"" attributes=""0"" /> </scope> <scope startOffset=""0xa8"" endOffset=""0xb6""> <local name=""i"" il_index=""4"" il_start=""0xa8"" il_end=""0xb6"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")] public void TestSignificanceOfDynamicVersusObjectAndTupleNamesInUniquenessOfPatternMatchingTemps() { var source = @"using System; public class Generic<T,U> { } class Program { public static void Main(string[] args) { var g = new Generic<object, (int, int)>(); M2(g, true, false, false); M2(g, false, true, false); M2(g, false, false, true); } public static void M2(object o, bool b1, bool b2, bool b3) { switch (o) { case Generic<object, (int a, int b)> g when b1: Console.Write(""a""); break; case var _ when b2: Console.Write(""b""); break; case Generic<dynamic, (int x, int y)> g when b3: Console.Write(""c""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication)) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "abc"); compVerifier.VerifyIL("Program.M2", @"{ // Code size 98 (0x62) .maxstack 2 .locals init (int V_0, Generic<object, System.ValueTuple<int, int>> V_1, //g Generic<dynamic, System.ValueTuple<int, int>> V_2, //g object V_3, object V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.s V_4 IL_0004: ldloc.s V_4 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: isinst ""Generic<object, System.ValueTuple<int, int>>"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0013 IL_0011: br.s IL_0029 IL_0013: ldarg.1 IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0025 IL_0018: ldstr ""a"" IL_001d: call ""void System.Console.Write(string)"" IL_0022: nop IL_0023: br.s IL_0061 IL_0025: ldc.i4.1 IL_0026: stloc.0 IL_0027: br.s IL_002d IL_0029: ldc.i4.3 IL_002a: stloc.0 IL_002b: br.s IL_002d IL_002d: ldarg.2 IL_002e: brtrue.s IL_0040 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: beq.s IL_003c IL_0034: br.s IL_0036 IL_0036: ldloc.0 IL_0037: ldc.i4.3 IL_0038: beq.s IL_003e IL_003a: br.s IL_0040 IL_003c: br.s IL_004d IL_003e: br.s IL_0061 IL_0040: ldstr ""b"" IL_0045: call ""void System.Console.Write(string)"" IL_004a: nop IL_004b: br.s IL_0061 IL_004d: ldloc.1 IL_004e: stloc.2 IL_004f: ldarg.3 IL_0050: brtrue.s IL_0054 IL_0052: br.s IL_0061 IL_0054: ldstr ""c"" IL_0059: call ""void System.Console.Write(string)"" IL_005e: nop IL_005f: br.s IL_0061 IL_0061: ret } " ); } [Fact] [WorkItem(39564, "https://github.com/dotnet/roslyn/issues/39564")] public void OrderOfEvaluationOfTupleAsSwitchExpressionArgument() { var source = @"using System; class Program { public static void Main(string[] args) { using var sr = new System.IO.StringReader(""fiz\nbar""); var r = (sr.ReadLine(), sr.ReadLine()) switch { (""fiz"", ""bar"") => ""Yep, all good!"", var (a, b) => $""Wait, what? I got ({a}, {b})!"", }; Console.WriteLine(r); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!"); compVerifier.VerifyIL("Program.Main", @" { // Code size 144 (0x90) .maxstack 4 .locals init (System.IO.StringReader V_0, //sr string V_1, //r string V_2, //a string V_3, //b string V_4) IL_0000: nop IL_0001: ldstr ""fiz bar"" IL_0006: newobj ""System.IO.StringReader..ctor(string)"" IL_000b: stloc.0 .try { IL_000c: ldloc.0 IL_000d: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0012: stloc.2 IL_0013: ldloc.0 IL_0014: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0019: stloc.3 IL_001a: ldc.i4.1 IL_001b: brtrue.s IL_001e IL_001d: nop IL_001e: ldloc.2 IL_001f: ldstr ""fiz"" IL_0024: call ""bool string.op_Equality(string, string)"" IL_0029: brfalse.s IL_0043 IL_002b: ldloc.3 IL_002c: ldstr ""bar"" IL_0031: call ""bool string.op_Equality(string, string)"" IL_0036: brtrue.s IL_003a IL_0038: br.s IL_0043 IL_003a: ldstr ""Yep, all good!"" IL_003f: stloc.s V_4 IL_0041: br.s IL_0074 IL_0043: br.s IL_0045 IL_0045: ldc.i4.5 IL_0046: newarr ""string"" IL_004b: dup IL_004c: ldc.i4.0 IL_004d: ldstr ""Wait, what? I got ("" IL_0052: stelem.ref IL_0053: dup IL_0054: ldc.i4.1 IL_0055: ldloc.2 IL_0056: stelem.ref IL_0057: dup IL_0058: ldc.i4.2 IL_0059: ldstr "", "" IL_005e: stelem.ref IL_005f: dup IL_0060: ldc.i4.3 IL_0061: ldloc.3 IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.4 IL_0065: ldstr "")!"" IL_006a: stelem.ref IL_006b: call ""string string.Concat(params string[])"" IL_0070: stloc.s V_4 IL_0072: br.s IL_0074 IL_0074: ldc.i4.1 IL_0075: brtrue.s IL_0078 IL_0077: nop IL_0078: ldloc.s V_4 IL_007a: stloc.1 IL_007b: ldloc.1 IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: nop IL_0082: leave.s IL_008f } finally { IL_0084: ldloc.0 IL_0085: brfalse.s IL_008e IL_0087: ldloc.0 IL_0088: callvirt ""void System.IDisposable.Dispose()"" IL_008d: nop IL_008e: endfinally } IL_008f: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe) .VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!"); compVerifier.VerifyIL("Program.Main", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.IO.StringReader V_0, //sr string V_1, //a string V_2, //b string V_3) IL_0000: ldstr ""fiz bar"" IL_0005: newobj ""System.IO.StringReader..ctor(string)"" IL_000a: stloc.0 .try { IL_000b: ldloc.0 IL_000c: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: callvirt ""string System.IO.TextReader.ReadLine()"" IL_0018: stloc.2 IL_0019: ldloc.1 IL_001a: ldstr ""fiz"" IL_001f: call ""bool string.op_Equality(string, string)"" IL_0024: brfalse.s IL_003b IL_0026: ldloc.2 IL_0027: ldstr ""bar"" IL_002c: call ""bool string.op_Equality(string, string)"" IL_0031: brfalse.s IL_003b IL_0033: ldstr ""Yep, all good!"" IL_0038: stloc.3 IL_0039: br.s IL_0067 IL_003b: ldc.i4.5 IL_003c: newarr ""string"" IL_0041: dup IL_0042: ldc.i4.0 IL_0043: ldstr ""Wait, what? I got ("" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldloc.1 IL_004c: stelem.ref IL_004d: dup IL_004e: ldc.i4.2 IL_004f: ldstr "", "" IL_0054: stelem.ref IL_0055: dup IL_0056: ldc.i4.3 IL_0057: ldloc.2 IL_0058: stelem.ref IL_0059: dup IL_005a: ldc.i4.4 IL_005b: ldstr "")!"" IL_0060: stelem.ref IL_0061: call ""string string.Concat(params string[])"" IL_0066: stloc.3 IL_0067: ldloc.3 IL_0068: call ""void System.Console.WriteLine(string)"" IL_006d: leave.s IL_0079 } finally { IL_006f: ldloc.0 IL_0070: brfalse.s IL_0078 IL_0072: ldloc.0 IL_0073: callvirt ""void System.IDisposable.Dispose()"" IL_0078: endfinally } IL_0079: ret } "); } [Fact] [WorkItem(41502, "https://github.com/dotnet/roslyn/issues/41502")] public void PatternSwitchDagReduction_01() { var source = @"using System; class Program { public static void Main(string[] args) { M(1, 1, 6); // 1 M(1, 2, 6); // 2 M(1, 1, 3); // 3 M(1, 2, 3); // 3 M(1, 5, 3); // 3 M(2, 5, 3); // 3 M(1, 3, 4); // 4 M(2, 1, 4); // 5 M(2, 2, 2); // 6 } public static void M(int a, int b, int c) => Console.Write(M2(a, b, c)); public static int M2(int a, int b, int c) => (a, b, c) switch { (1, 1, 6) => 1, (1, 2, 6) => 2, (_, _, 3) => 3, (1, _, _) => 4, (_, 1, _) => 5, (_, _, _) => 6, }; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); var compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456"); compVerifier.VerifyIL("Program.M2", @" { // Code size 76 (0x4c) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.0 IL_0005: ldc.i4.1 IL_0006: bne.un.s IL_0024 IL_0008: ldarg.1 IL_0009: ldc.i4.1 IL_000a: beq.s IL_0014 IL_000c: br.s IL_000e IL_000e: ldarg.1 IL_000f: ldc.i4.2 IL_0010: beq.s IL_001a IL_0012: br.s IL_001e IL_0014: ldarg.2 IL_0015: ldc.i4.6 IL_0016: beq.s IL_002e IL_0018: br.s IL_001e IL_001a: ldarg.2 IL_001b: ldc.i4.6 IL_001c: beq.s IL_0032 IL_001e: ldarg.2 IL_001f: ldc.i4.3 IL_0020: beq.s IL_0036 IL_0022: br.s IL_003a IL_0024: ldarg.2 IL_0025: ldc.i4.3 IL_0026: beq.s IL_0036 IL_0028: ldarg.1 IL_0029: ldc.i4.1 IL_002a: beq.s IL_003e IL_002c: br.s IL_0042 IL_002e: ldc.i4.1 IL_002f: stloc.0 IL_0030: br.s IL_0046 IL_0032: ldc.i4.2 IL_0033: stloc.0 IL_0034: br.s IL_0046 IL_0036: ldc.i4.3 IL_0037: stloc.0 IL_0038: br.s IL_0046 IL_003a: ldc.i4.4 IL_003b: stloc.0 IL_003c: br.s IL_0046 IL_003e: ldc.i4.5 IL_003f: stloc.0 IL_0040: br.s IL_0046 IL_0042: ldc.i4.6 IL_0043: stloc.0 IL_0044: br.s IL_0046 IL_0046: ldc.i4.1 IL_0047: brtrue.s IL_004a IL_0049: nop IL_004a: ldloc.0 IL_004b: ret } "); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456"); compVerifier.VerifyIL("Program.M2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: bne.un.s IL_001e IL_0004: ldarg.1 IL_0005: ldc.i4.1 IL_0006: beq.s IL_000e IL_0008: ldarg.1 IL_0009: ldc.i4.2 IL_000a: beq.s IL_0014 IL_000c: br.s IL_0018 IL_000e: ldarg.2 IL_000f: ldc.i4.6 IL_0010: beq.s IL_0028 IL_0012: br.s IL_0018 IL_0014: ldarg.2 IL_0015: ldc.i4.6 IL_0016: beq.s IL_002c IL_0018: ldarg.2 IL_0019: ldc.i4.3 IL_001a: beq.s IL_0030 IL_001c: br.s IL_0034 IL_001e: ldarg.2 IL_001f: ldc.i4.3 IL_0020: beq.s IL_0030 IL_0022: ldarg.1 IL_0023: ldc.i4.1 IL_0024: beq.s IL_0038 IL_0026: br.s IL_003c IL_0028: ldc.i4.1 IL_0029: stloc.0 IL_002a: br.s IL_003e IL_002c: ldc.i4.2 IL_002d: stloc.0 IL_002e: br.s IL_003e IL_0030: ldc.i4.3 IL_0031: stloc.0 IL_0032: br.s IL_003e IL_0034: ldc.i4.4 IL_0035: stloc.0 IL_0036: br.s IL_003e IL_0038: ldc.i4.5 IL_0039: stloc.0 IL_003a: br.s IL_003e IL_003c: ldc.i4.6 IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: ret } "); } #endregion "regression tests" #region Code Quality tests [Fact] public void BalancedSwitchDispatch_Double() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1D)); Console.WriteLine(M(3.1D)); Console.WriteLine(M(4.1D)); Console.WriteLine(M(5.1D)); Console.WriteLine(M(6.1D)); Console.WriteLine(M(7.1D)); Console.WriteLine(M(8.1D)); Console.WriteLine(M(9.1D)); Console.WriteLine(M(10.1D)); Console.WriteLine(M(11.1D)); Console.WriteLine(M(12.1D)); Console.WriteLine(M(13.1D)); Console.WriteLine(M(14.1D)); Console.WriteLine(M(15.1D)); Console.WriteLine(M(16.1D)); Console.WriteLine(M(17.1D)); Console.WriteLine(M(18.1D)); Console.WriteLine(M(19.1D)); Console.WriteLine(M(20.1D)); Console.WriteLine(M(21.1D)); Console.WriteLine(M(22.1D)); Console.WriteLine(M(23.1D)); Console.WriteLine(M(24.1D)); Console.WriteLine(M(25.1D)); Console.WriteLine(M(26.1D)); Console.WriteLine(M(27.1D)); Console.WriteLine(M(28.1D)); Console.WriteLine(M(29.1D)); } static int M(double d) { return d switch { >= 27.1D and < 29.1D => 19, 26.1D => 18, 9.1D => 5, >= 2.1D and < 4.1D => 1, 12.1D => 8, >= 21.1D and < 23.1D => 15, 19.1D => 13, 29.1D => 20, >= 13.1D and < 15.1D => 9, 10.1D => 6, 15.1D => 10, 11.1D => 7, 4.1D => 2, >= 16.1D and < 18.1D => 11, >= 23.1D and < 25.1D => 16, 18.1D => 12, >= 7.1D and < 9.1D => 4, 25.1D => 17, 20.1D => 14, >= 5.1D and < 7.1D => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 499 (0x1f3) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.r8 13.1 IL_000a: blt.un IL_00fb IL_000f: ldarg.0 IL_0010: ldc.r8 21.1 IL_0019: blt.un.s IL_008b IL_001b: ldarg.0 IL_001c: ldc.r8 27.1 IL_0025: blt.un.s IL_004a IL_0027: ldarg.0 IL_0028: ldc.r8 29.1 IL_0031: blt IL_0193 IL_0036: ldarg.0 IL_0037: ldc.r8 29.1 IL_0040: beq IL_01b3 IL_0045: br IL_01ef IL_004a: ldarg.0 IL_004b: ldc.r8 23.1 IL_0054: blt IL_01a9 IL_0059: ldarg.0 IL_005a: ldc.r8 25.1 IL_0063: blt IL_01d3 IL_0068: ldarg.0 IL_0069: ldc.r8 25.1 IL_0072: beq IL_01e1 IL_0077: ldarg.0 IL_0078: ldc.r8 26.1 IL_0081: beq IL_0198 IL_0086: br IL_01ef IL_008b: ldarg.0 IL_008c: ldc.r8 16.1 IL_0095: blt.un.s IL_00d8 IL_0097: ldarg.0 IL_0098: ldc.r8 18.1 IL_00a1: blt IL_01ce IL_00a6: ldarg.0 IL_00a7: ldc.r8 18.1 IL_00b0: beq IL_01d8 IL_00b5: ldarg.0 IL_00b6: ldc.r8 19.1 IL_00bf: beq IL_01ae IL_00c4: ldarg.0 IL_00c5: ldc.r8 20.1 IL_00ce: beq IL_01e6 IL_00d3: br IL_01ef IL_00d8: ldarg.0 IL_00d9: ldc.r8 15.1 IL_00e2: blt IL_01b8 IL_00e7: ldarg.0 IL_00e8: ldc.r8 15.1 IL_00f1: beq IL_01c1 IL_00f6: br IL_01ef IL_00fb: ldarg.0 IL_00fc: ldc.r8 7.1 IL_0105: blt.un.s IL_015f IL_0107: ldarg.0 IL_0108: ldc.r8 9.1 IL_0111: blt IL_01dd IL_0116: ldarg.0 IL_0117: ldc.r8 10.1 IL_0120: bgt.un.s IL_0142 IL_0122: ldarg.0 IL_0123: ldc.r8 9.1 IL_012c: beq.s IL_019d IL_012e: ldarg.0 IL_012f: ldc.r8 10.1 IL_0138: beq IL_01bd IL_013d: br IL_01ef IL_0142: ldarg.0 IL_0143: ldc.r8 11.1 IL_014c: beq.s IL_01c6 IL_014e: ldarg.0 IL_014f: ldc.r8 12.1 IL_0158: beq.s IL_01a5 IL_015a: br IL_01ef IL_015f: ldarg.0 IL_0160: ldc.r8 4.1 IL_0169: bge.un.s IL_0179 IL_016b: ldarg.0 IL_016c: ldc.r8 2.1 IL_0175: bge.s IL_01a1 IL_0177: br.s IL_01ef IL_0179: ldarg.0 IL_017a: ldc.r8 5.1 IL_0183: bge.s IL_01eb IL_0185: ldarg.0 IL_0186: ldc.r8 4.1 IL_018f: beq.s IL_01ca IL_0191: br.s IL_01ef IL_0193: ldc.i4.s 19 IL_0195: stloc.0 IL_0196: br.s IL_01f1 IL_0198: ldc.i4.s 18 IL_019a: stloc.0 IL_019b: br.s IL_01f1 IL_019d: ldc.i4.5 IL_019e: stloc.0 IL_019f: br.s IL_01f1 IL_01a1: ldc.i4.1 IL_01a2: stloc.0 IL_01a3: br.s IL_01f1 IL_01a5: ldc.i4.8 IL_01a6: stloc.0 IL_01a7: br.s IL_01f1 IL_01a9: ldc.i4.s 15 IL_01ab: stloc.0 IL_01ac: br.s IL_01f1 IL_01ae: ldc.i4.s 13 IL_01b0: stloc.0 IL_01b1: br.s IL_01f1 IL_01b3: ldc.i4.s 20 IL_01b5: stloc.0 IL_01b6: br.s IL_01f1 IL_01b8: ldc.i4.s 9 IL_01ba: stloc.0 IL_01bb: br.s IL_01f1 IL_01bd: ldc.i4.6 IL_01be: stloc.0 IL_01bf: br.s IL_01f1 IL_01c1: ldc.i4.s 10 IL_01c3: stloc.0 IL_01c4: br.s IL_01f1 IL_01c6: ldc.i4.7 IL_01c7: stloc.0 IL_01c8: br.s IL_01f1 IL_01ca: ldc.i4.2 IL_01cb: stloc.0 IL_01cc: br.s IL_01f1 IL_01ce: ldc.i4.s 11 IL_01d0: stloc.0 IL_01d1: br.s IL_01f1 IL_01d3: ldc.i4.s 16 IL_01d5: stloc.0 IL_01d6: br.s IL_01f1 IL_01d8: ldc.i4.s 12 IL_01da: stloc.0 IL_01db: br.s IL_01f1 IL_01dd: ldc.i4.4 IL_01de: stloc.0 IL_01df: br.s IL_01f1 IL_01e1: ldc.i4.s 17 IL_01e3: stloc.0 IL_01e4: br.s IL_01f1 IL_01e6: ldc.i4.s 14 IL_01e8: stloc.0 IL_01e9: br.s IL_01f1 IL_01eb: ldc.i4.3 IL_01ec: stloc.0 IL_01ed: br.s IL_01f1 IL_01ef: ldc.i4.0 IL_01f0: stloc.0 IL_01f1: ldloc.0 IL_01f2: ret } " ); } [Fact] public void BalancedSwitchDispatch_Float() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1F)); Console.WriteLine(M(3.1F)); Console.WriteLine(M(4.1F)); Console.WriteLine(M(5.1F)); Console.WriteLine(M(6.1F)); Console.WriteLine(M(7.1F)); Console.WriteLine(M(8.1F)); Console.WriteLine(M(9.1F)); Console.WriteLine(M(10.1F)); Console.WriteLine(M(11.1F)); Console.WriteLine(M(12.1F)); Console.WriteLine(M(13.1F)); Console.WriteLine(M(14.1F)); Console.WriteLine(M(15.1F)); Console.WriteLine(M(16.1F)); Console.WriteLine(M(17.1F)); Console.WriteLine(M(18.1F)); Console.WriteLine(M(19.1F)); Console.WriteLine(M(20.1F)); Console.WriteLine(M(21.1F)); Console.WriteLine(M(22.1F)); Console.WriteLine(M(23.1F)); Console.WriteLine(M(24.1F)); Console.WriteLine(M(25.1F)); Console.WriteLine(M(26.1F)); Console.WriteLine(M(27.1F)); Console.WriteLine(M(28.1F)); Console.WriteLine(M(29.1F)); } static int M(float d) { return d switch { >= 27.1F and < 29.1F => 19, 26.1F => 18, 9.1F => 5, >= 2.1F and < 4.1F => 1, 12.1F => 8, >= 21.1F and < 23.1F => 15, 19.1F => 13, 29.1F => 20, >= 13.1F and < 15.1F => 9, 10.1F => 6, 15.1F => 10, 11.1F => 7, 4.1F => 2, >= 16.1F and < 18.1F => 11, >= 23.1F and < 25.1F => 16, 18.1F => 12, >= 7.1F and < 9.1F => 4, 25.1F => 17, 20.1F => 14, >= 5.1F and < 7.1F => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 388 (0x184) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.r4 13.1 IL_0006: blt.un IL_00bb IL_000b: ldarg.0 IL_000c: ldc.r4 21.1 IL_0011: blt.un.s IL_0067 IL_0013: ldarg.0 IL_0014: ldc.r4 27.1 IL_0019: blt.un.s IL_0036 IL_001b: ldarg.0 IL_001c: ldc.r4 29.1 IL_0021: blt IL_0124 IL_0026: ldarg.0 IL_0027: ldc.r4 29.1 IL_002c: beq IL_0144 IL_0031: br IL_0180 IL_0036: ldarg.0 IL_0037: ldc.r4 23.1 IL_003c: blt IL_013a IL_0041: ldarg.0 IL_0042: ldc.r4 25.1 IL_0047: blt IL_0164 IL_004c: ldarg.0 IL_004d: ldc.r4 25.1 IL_0052: beq IL_0172 IL_0057: ldarg.0 IL_0058: ldc.r4 26.1 IL_005d: beq IL_0129 IL_0062: br IL_0180 IL_0067: ldarg.0 IL_0068: ldc.r4 16.1 IL_006d: blt.un.s IL_00a0 IL_006f: ldarg.0 IL_0070: ldc.r4 18.1 IL_0075: blt IL_015f IL_007a: ldarg.0 IL_007b: ldc.r4 18.1 IL_0080: beq IL_0169 IL_0085: ldarg.0 IL_0086: ldc.r4 19.1 IL_008b: beq IL_013f IL_0090: ldarg.0 IL_0091: ldc.r4 20.1 IL_0096: beq IL_0177 IL_009b: br IL_0180 IL_00a0: ldarg.0 IL_00a1: ldc.r4 15.1 IL_00a6: blt IL_0149 IL_00ab: ldarg.0 IL_00ac: ldc.r4 15.1 IL_00b1: beq IL_0152 IL_00b6: br IL_0180 IL_00bb: ldarg.0 IL_00bc: ldc.r4 7.1 IL_00c1: blt.un.s IL_0100 IL_00c3: ldarg.0 IL_00c4: ldc.r4 9.1 IL_00c9: blt IL_016e IL_00ce: ldarg.0 IL_00cf: ldc.r4 10.1 IL_00d4: bgt.un.s IL_00eb IL_00d6: ldarg.0 IL_00d7: ldc.r4 9.1 IL_00dc: beq.s IL_012e IL_00de: ldarg.0 IL_00df: ldc.r4 10.1 IL_00e4: beq.s IL_014e IL_00e6: br IL_0180 IL_00eb: ldarg.0 IL_00ec: ldc.r4 11.1 IL_00f1: beq.s IL_0157 IL_00f3: ldarg.0 IL_00f4: ldc.r4 12.1 IL_00f9: beq.s IL_0136 IL_00fb: br IL_0180 IL_0100: ldarg.0 IL_0101: ldc.r4 4.1 IL_0106: bge.un.s IL_0112 IL_0108: ldarg.0 IL_0109: ldc.r4 2.1 IL_010e: bge.s IL_0132 IL_0110: br.s IL_0180 IL_0112: ldarg.0 IL_0113: ldc.r4 5.1 IL_0118: bge.s IL_017c IL_011a: ldarg.0 IL_011b: ldc.r4 4.1 IL_0120: beq.s IL_015b IL_0122: br.s IL_0180 IL_0124: ldc.i4.s 19 IL_0126: stloc.0 IL_0127: br.s IL_0182 IL_0129: ldc.i4.s 18 IL_012b: stloc.0 IL_012c: br.s IL_0182 IL_012e: ldc.i4.5 IL_012f: stloc.0 IL_0130: br.s IL_0182 IL_0132: ldc.i4.1 IL_0133: stloc.0 IL_0134: br.s IL_0182 IL_0136: ldc.i4.8 IL_0137: stloc.0 IL_0138: br.s IL_0182 IL_013a: ldc.i4.s 15 IL_013c: stloc.0 IL_013d: br.s IL_0182 IL_013f: ldc.i4.s 13 IL_0141: stloc.0 IL_0142: br.s IL_0182 IL_0144: ldc.i4.s 20 IL_0146: stloc.0 IL_0147: br.s IL_0182 IL_0149: ldc.i4.s 9 IL_014b: stloc.0 IL_014c: br.s IL_0182 IL_014e: ldc.i4.6 IL_014f: stloc.0 IL_0150: br.s IL_0182 IL_0152: ldc.i4.s 10 IL_0154: stloc.0 IL_0155: br.s IL_0182 IL_0157: ldc.i4.7 IL_0158: stloc.0 IL_0159: br.s IL_0182 IL_015b: ldc.i4.2 IL_015c: stloc.0 IL_015d: br.s IL_0182 IL_015f: ldc.i4.s 11 IL_0161: stloc.0 IL_0162: br.s IL_0182 IL_0164: ldc.i4.s 16 IL_0166: stloc.0 IL_0167: br.s IL_0182 IL_0169: ldc.i4.s 12 IL_016b: stloc.0 IL_016c: br.s IL_0182 IL_016e: ldc.i4.4 IL_016f: stloc.0 IL_0170: br.s IL_0182 IL_0172: ldc.i4.s 17 IL_0174: stloc.0 IL_0175: br.s IL_0182 IL_0177: ldc.i4.s 14 IL_0179: stloc.0 IL_017a: br.s IL_0182 IL_017c: ldc.i4.3 IL_017d: stloc.0 IL_017e: br.s IL_0182 IL_0180: ldc.i4.0 IL_0181: stloc.0 IL_0182: ldloc.0 IL_0183: ret } " ); } [Fact] public void BalancedSwitchDispatch_Decimal() { var source = @"using System; class C { static void Main() { Console.WriteLine(M(2.1M)); Console.WriteLine(M(3.1M)); Console.WriteLine(M(4.1M)); Console.WriteLine(M(5.1M)); Console.WriteLine(M(6.1M)); Console.WriteLine(M(7.1M)); Console.WriteLine(M(8.1M)); Console.WriteLine(M(9.1M)); Console.WriteLine(M(10.1M)); Console.WriteLine(M(11.1M)); Console.WriteLine(M(12.1M)); Console.WriteLine(M(13.1M)); Console.WriteLine(M(14.1M)); Console.WriteLine(M(15.1M)); Console.WriteLine(M(16.1M)); Console.WriteLine(M(17.1M)); Console.WriteLine(M(18.1M)); Console.WriteLine(M(19.1M)); Console.WriteLine(M(20.1M)); Console.WriteLine(M(21.1M)); Console.WriteLine(M(22.1M)); Console.WriteLine(M(23.1M)); Console.WriteLine(M(24.1M)); Console.WriteLine(M(25.1M)); Console.WriteLine(M(26.1M)); Console.WriteLine(M(27.1M)); Console.WriteLine(M(28.1M)); Console.WriteLine(M(29.1M)); } static int M(decimal d) { return d switch { >= 27.1M and < 29.1M => 19, 26.1M => 18, 9.1M => 5, >= 2.1M and < 4.1M => 1, 12.1M => 8, >= 21.1M and < 23.1M => 15, 19.1M => 13, 29.1M => 20, >= 13.1M and < 15.1M => 9, 10.1M => 6, 15.1M => 10, 11.1M => 7, 4.1M => 2, >= 16.1M and < 18.1M => 11, >= 23.1M and < 25.1M => 16, 18.1M => 12, >= 7.1M and < 9.1M => 4, 25.1M => 17, 20.1M => 14, >= 5.1M and < 7.1M => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 751 (0x2ef) .maxstack 6 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4 0x83 IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000f: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0014: brfalse IL_019e IL_0019: ldarg.0 IL_001a: ldc.i4 0xd3 IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: ldc.i4.1 IL_0023: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0028: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_002d: brfalse IL_00e8 IL_0032: ldarg.0 IL_0033: ldc.i4 0x10f IL_0038: ldc.i4.0 IL_0039: ldc.i4.0 IL_003a: ldc.i4.0 IL_003b: ldc.i4.1 IL_003c: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0041: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0046: brfalse.s IL_007f IL_0048: ldarg.0 IL_0049: ldc.i4 0x123 IL_004e: ldc.i4.0 IL_004f: ldc.i4.0 IL_0050: ldc.i4.0 IL_0051: ldc.i4.1 IL_0052: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0057: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_005c: brtrue IL_028f IL_0061: ldarg.0 IL_0062: ldc.i4 0x123 IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldc.i4.0 IL_006a: ldc.i4.1 IL_006b: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0070: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0075: brtrue IL_02af IL_007a: br IL_02eb IL_007f: ldarg.0 IL_0080: ldc.i4 0xe7 IL_0085: ldc.i4.0 IL_0086: ldc.i4.0 IL_0087: ldc.i4.0 IL_0088: ldc.i4.1 IL_0089: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_008e: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_0093: brtrue IL_02a5 IL_0098: ldarg.0 IL_0099: ldc.i4 0xfb IL_009e: ldc.i4.0 IL_009f: ldc.i4.0 IL_00a0: ldc.i4.0 IL_00a1: ldc.i4.1 IL_00a2: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00a7: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_00ac: brtrue IL_02cf IL_00b1: ldarg.0 IL_00b2: ldc.i4 0xfb IL_00b7: ldc.i4.0 IL_00b8: ldc.i4.0 IL_00b9: ldc.i4.0 IL_00ba: ldc.i4.1 IL_00bb: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00c0: call ""bool decimal.op_Equality(decimal, decimal)"" IL_00c5: brtrue IL_02dd IL_00ca: ldarg.0 IL_00cb: ldc.i4 0x105 IL_00d0: ldc.i4.0 IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldc.i4.1 IL_00d4: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00d9: call ""bool decimal.op_Equality(decimal, decimal)"" IL_00de: brtrue IL_0294 IL_00e3: br IL_02eb IL_00e8: ldarg.0 IL_00e9: ldc.i4 0xa1 IL_00ee: ldc.i4.0 IL_00ef: ldc.i4.0 IL_00f0: ldc.i4.0 IL_00f1: ldc.i4.1 IL_00f2: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_00f7: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_00fc: brfalse.s IL_0167 IL_00fe: ldarg.0 IL_00ff: ldc.i4 0xb5 IL_0104: ldc.i4.0 IL_0105: ldc.i4.0 IL_0106: ldc.i4.0 IL_0107: ldc.i4.1 IL_0108: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_010d: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_0112: brtrue IL_02ca IL_0117: ldarg.0 IL_0118: ldc.i4 0xb5 IL_011d: ldc.i4.0 IL_011e: ldc.i4.0 IL_011f: ldc.i4.0 IL_0120: ldc.i4.1 IL_0121: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0126: call ""bool decimal.op_Equality(decimal, decimal)"" IL_012b: brtrue IL_02d4 IL_0130: ldarg.0 IL_0131: ldc.i4 0xbf IL_0136: ldc.i4.0 IL_0137: ldc.i4.0 IL_0138: ldc.i4.0 IL_0139: ldc.i4.1 IL_013a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_013f: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0144: brtrue IL_02aa IL_0149: ldarg.0 IL_014a: ldc.i4 0xc9 IL_014f: ldc.i4.0 IL_0150: ldc.i4.0 IL_0151: ldc.i4.0 IL_0152: ldc.i4.1 IL_0153: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0158: call ""bool decimal.op_Equality(decimal, decimal)"" IL_015d: brtrue IL_02e2 IL_0162: br IL_02eb IL_0167: ldarg.0 IL_0168: ldc.i4 0x97 IL_016d: ldc.i4.0 IL_016e: ldc.i4.0 IL_016f: ldc.i4.0 IL_0170: ldc.i4.1 IL_0171: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0176: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_017b: brtrue IL_02b4 IL_0180: ldarg.0 IL_0181: ldc.i4 0x97 IL_0186: ldc.i4.0 IL_0187: ldc.i4.0 IL_0188: ldc.i4.0 IL_0189: ldc.i4.1 IL_018a: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_018f: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0194: brtrue IL_02bd IL_0199: br IL_02eb IL_019e: ldarg.0 IL_019f: ldc.i4.s 71 IL_01a1: ldc.i4.0 IL_01a2: ldc.i4.0 IL_01a3: ldc.i4.0 IL_01a4: ldc.i4.1 IL_01a5: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01aa: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_01af: brfalse IL_023c IL_01b4: ldarg.0 IL_01b5: ldc.i4.s 91 IL_01b7: ldc.i4.0 IL_01b8: ldc.i4.0 IL_01b9: ldc.i4.0 IL_01ba: ldc.i4.1 IL_01bb: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01c0: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_01c5: brtrue IL_02d9 IL_01ca: ldarg.0 IL_01cb: ldc.i4.s 101 IL_01cd: ldc.i4.0 IL_01ce: ldc.i4.0 IL_01cf: ldc.i4.0 IL_01d0: ldc.i4.1 IL_01d1: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01d6: call ""bool decimal.op_LessThanOrEqual(decimal, decimal)"" IL_01db: brfalse.s IL_020e IL_01dd: ldarg.0 IL_01de: ldc.i4.s 91 IL_01e0: ldc.i4.0 IL_01e1: ldc.i4.0 IL_01e2: ldc.i4.0 IL_01e3: ldc.i4.1 IL_01e4: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01e9: call ""bool decimal.op_Equality(decimal, decimal)"" IL_01ee: brtrue IL_0299 IL_01f3: ldarg.0 IL_01f4: ldc.i4.s 101 IL_01f6: ldc.i4.0 IL_01f7: ldc.i4.0 IL_01f8: ldc.i4.0 IL_01f9: ldc.i4.1 IL_01fa: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_01ff: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0204: brtrue IL_02b9 IL_0209: br IL_02eb IL_020e: ldarg.0 IL_020f: ldc.i4.s 111 IL_0211: ldc.i4.0 IL_0212: ldc.i4.0 IL_0213: ldc.i4.0 IL_0214: ldc.i4.1 IL_0215: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_021a: call ""bool decimal.op_Equality(decimal, decimal)"" IL_021f: brtrue IL_02c2 IL_0224: ldarg.0 IL_0225: ldc.i4.s 121 IL_0227: ldc.i4.0 IL_0228: ldc.i4.0 IL_0229: ldc.i4.0 IL_022a: ldc.i4.1 IL_022b: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0230: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0235: brtrue.s IL_02a1 IL_0237: br IL_02eb IL_023c: ldarg.0 IL_023d: ldc.i4.s 41 IL_023f: ldc.i4.0 IL_0240: ldc.i4.0 IL_0241: ldc.i4.0 IL_0242: ldc.i4.1 IL_0243: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0248: call ""bool decimal.op_LessThan(decimal, decimal)"" IL_024d: brfalse.s IL_0267 IL_024f: ldarg.0 IL_0250: ldc.i4.s 21 IL_0252: ldc.i4.0 IL_0253: ldc.i4.0 IL_0254: ldc.i4.0 IL_0255: ldc.i4.1 IL_0256: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_025b: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0260: brtrue.s IL_029d IL_0262: br IL_02eb IL_0267: ldarg.0 IL_0268: ldc.i4.s 51 IL_026a: ldc.i4.0 IL_026b: ldc.i4.0 IL_026c: ldc.i4.0 IL_026d: ldc.i4.1 IL_026e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0273: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)"" IL_0278: brtrue.s IL_02e7 IL_027a: ldarg.0 IL_027b: ldc.i4.s 41 IL_027d: ldc.i4.0 IL_027e: ldc.i4.0 IL_027f: ldc.i4.0 IL_0280: ldc.i4.1 IL_0281: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0286: call ""bool decimal.op_Equality(decimal, decimal)"" IL_028b: brtrue.s IL_02c6 IL_028d: br.s IL_02eb IL_028f: ldc.i4.s 19 IL_0291: stloc.0 IL_0292: br.s IL_02ed IL_0294: ldc.i4.s 18 IL_0296: stloc.0 IL_0297: br.s IL_02ed IL_0299: ldc.i4.5 IL_029a: stloc.0 IL_029b: br.s IL_02ed IL_029d: ldc.i4.1 IL_029e: stloc.0 IL_029f: br.s IL_02ed IL_02a1: ldc.i4.8 IL_02a2: stloc.0 IL_02a3: br.s IL_02ed IL_02a5: ldc.i4.s 15 IL_02a7: stloc.0 IL_02a8: br.s IL_02ed IL_02aa: ldc.i4.s 13 IL_02ac: stloc.0 IL_02ad: br.s IL_02ed IL_02af: ldc.i4.s 20 IL_02b1: stloc.0 IL_02b2: br.s IL_02ed IL_02b4: ldc.i4.s 9 IL_02b6: stloc.0 IL_02b7: br.s IL_02ed IL_02b9: ldc.i4.6 IL_02ba: stloc.0 IL_02bb: br.s IL_02ed IL_02bd: ldc.i4.s 10 IL_02bf: stloc.0 IL_02c0: br.s IL_02ed IL_02c2: ldc.i4.7 IL_02c3: stloc.0 IL_02c4: br.s IL_02ed IL_02c6: ldc.i4.2 IL_02c7: stloc.0 IL_02c8: br.s IL_02ed IL_02ca: ldc.i4.s 11 IL_02cc: stloc.0 IL_02cd: br.s IL_02ed IL_02cf: ldc.i4.s 16 IL_02d1: stloc.0 IL_02d2: br.s IL_02ed IL_02d4: ldc.i4.s 12 IL_02d6: stloc.0 IL_02d7: br.s IL_02ed IL_02d9: ldc.i4.4 IL_02da: stloc.0 IL_02db: br.s IL_02ed IL_02dd: ldc.i4.s 17 IL_02df: stloc.0 IL_02e0: br.s IL_02ed IL_02e2: ldc.i4.s 14 IL_02e4: stloc.0 IL_02e5: br.s IL_02ed IL_02e7: ldc.i4.3 IL_02e8: stloc.0 IL_02e9: br.s IL_02ed IL_02eb: ldc.i4.0 IL_02ec: stloc.0 IL_02ed: ldloc.0 IL_02ee: ret } " ); } [Fact] public void BalancedSwitchDispatch_Uint32() { // We do not currently detect that the set of values that we are dispatching on is a compact set, // which would enable us to use the IL switch instruction even though the input was expressed using // a set of relational comparisons. var source = @"using System; class C { static void Main() { Console.WriteLine(M(2U)); Console.WriteLine(M(3U)); Console.WriteLine(M(4U)); Console.WriteLine(M(5U)); Console.WriteLine(M(6U)); Console.WriteLine(M(7U)); Console.WriteLine(M(8U)); Console.WriteLine(M(9U)); Console.WriteLine(M(10U)); Console.WriteLine(M(11U)); Console.WriteLine(M(12U)); Console.WriteLine(M(13U)); Console.WriteLine(M(14U)); Console.WriteLine(M(15U)); Console.WriteLine(M(16U)); Console.WriteLine(M(17U)); Console.WriteLine(M(18U)); Console.WriteLine(M(19U)); Console.WriteLine(M(20U)); Console.WriteLine(M(21U)); Console.WriteLine(M(22U)); Console.WriteLine(M(23U)); Console.WriteLine(M(24U)); Console.WriteLine(M(25U)); Console.WriteLine(M(26U)); Console.WriteLine(M(27U)); Console.WriteLine(M(28U)); Console.WriteLine(M(29U)); } static int M(uint d) { return d switch { >= 27U and < 29U => 19, 26U => 18, 9U => 5, >= 2U and < 4U => 1, 12U => 8, >= 21U and < 23U => 15, 19U => 13, 29U => 20, >= 13U and < 15U => 9, 10U => 6, 15U => 10, 11U => 7, 4U => 2, >= 16U and < 18U => 11, >= 23U and < 25U => 16, 18U => 12, >= 7U and < 9U => 4, 25U => 17, 20U => 14, >= 5U and < 7U => 3, _ => 0, }; } } "; var expectedOutput = @"1 1 2 3 3 4 4 5 6 7 8 9 9 10 11 11 12 13 14 15 15 16 16 17 18 19 19 20 "; var compVerifier = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication), parseOptions: TestOptions.RegularWithPatternCombinators, expectedOutput: expectedOutput); compVerifier.VerifyIL("C.M", @" { // Code size 243 (0xf3) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.s 21 IL_0003: blt.un.s IL_0039 IL_0005: ldarg.0 IL_0006: ldc.i4.s 27 IL_0008: blt.un.s IL_001f IL_000a: ldarg.0 IL_000b: ldc.i4.s 29 IL_000d: blt.un IL_0093 IL_0012: ldarg.0 IL_0013: ldc.i4.s 29 IL_0015: beq IL_00b3 IL_001a: br IL_00ef IL_001f: ldarg.0 IL_0020: ldc.i4.s 23 IL_0022: blt.un IL_00a9 IL_0027: ldarg.0 IL_0028: ldc.i4.s 25 IL_002a: blt.un IL_00d3 IL_002f: ldarg.0 IL_0030: ldc.i4.s 26 IL_0032: beq.s IL_0098 IL_0034: br IL_00e1 IL_0039: ldarg.0 IL_003a: ldc.i4.s 13 IL_003c: blt.un.s IL_0061 IL_003e: ldarg.0 IL_003f: ldc.i4.s 15 IL_0041: blt.un.s IL_00b8 IL_0043: ldarg.0 IL_0044: ldc.i4.s 18 IL_0046: bge.un.s IL_004f IL_0048: ldarg.0 IL_0049: ldc.i4.s 15 IL_004b: beq.s IL_00c1 IL_004d: br.s IL_00ce IL_004f: ldarg.0 IL_0050: ldc.i4.s 18 IL_0052: beq IL_00d8 IL_0057: ldarg.0 IL_0058: ldc.i4.s 19 IL_005a: beq.s IL_00ae IL_005c: br IL_00e6 IL_0061: ldarg.0 IL_0062: ldc.i4.4 IL_0063: bge.un.s IL_006e IL_0065: ldarg.0 IL_0066: ldc.i4.2 IL_0067: bge.un.s IL_00a1 IL_0069: br IL_00ef IL_006e: ldarg.0 IL_006f: ldc.i4.7 IL_0070: blt.un.s IL_008d IL_0072: ldarg.0 IL_0073: ldc.i4.s 9 IL_0075: sub IL_0076: switch ( IL_009d, IL_00bd, IL_00c6, IL_00a5) IL_008b: br.s IL_00dd IL_008d: ldarg.0 IL_008e: ldc.i4.4 IL_008f: beq.s IL_00ca IL_0091: br.s IL_00eb IL_0093: ldc.i4.s 19 IL_0095: stloc.0 IL_0096: br.s IL_00f1 IL_0098: ldc.i4.s 18 IL_009a: stloc.0 IL_009b: br.s IL_00f1 IL_009d: ldc.i4.5 IL_009e: stloc.0 IL_009f: br.s IL_00f1 IL_00a1: ldc.i4.1 IL_00a2: stloc.0 IL_00a3: br.s IL_00f1 IL_00a5: ldc.i4.8 IL_00a6: stloc.0 IL_00a7: br.s IL_00f1 IL_00a9: ldc.i4.s 15 IL_00ab: stloc.0 IL_00ac: br.s IL_00f1 IL_00ae: ldc.i4.s 13 IL_00b0: stloc.0 IL_00b1: br.s IL_00f1 IL_00b3: ldc.i4.s 20 IL_00b5: stloc.0 IL_00b6: br.s IL_00f1 IL_00b8: ldc.i4.s 9 IL_00ba: stloc.0 IL_00bb: br.s IL_00f1 IL_00bd: ldc.i4.6 IL_00be: stloc.0 IL_00bf: br.s IL_00f1 IL_00c1: ldc.i4.s 10 IL_00c3: stloc.0 IL_00c4: br.s IL_00f1 IL_00c6: ldc.i4.7 IL_00c7: stloc.0 IL_00c8: br.s IL_00f1 IL_00ca: ldc.i4.2 IL_00cb: stloc.0 IL_00cc: br.s IL_00f1 IL_00ce: ldc.i4.s 11 IL_00d0: stloc.0 IL_00d1: br.s IL_00f1 IL_00d3: ldc.i4.s 16 IL_00d5: stloc.0 IL_00d6: br.s IL_00f1 IL_00d8: ldc.i4.s 12 IL_00da: stloc.0 IL_00db: br.s IL_00f1 IL_00dd: ldc.i4.4 IL_00de: stloc.0 IL_00df: br.s IL_00f1 IL_00e1: ldc.i4.s 17 IL_00e3: stloc.0 IL_00e4: br.s IL_00f1 IL_00e6: ldc.i4.s 14 IL_00e8: stloc.0 IL_00e9: br.s IL_00f1 IL_00eb: ldc.i4.3 IL_00ec: stloc.0 IL_00ed: br.s IL_00f1 IL_00ef: ldc.i4.0 IL_00f0: stloc.0 IL_00f1: ldloc.0 IL_00f2: ret } " ); } #endregion Code Quality tests } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharp/FindUsages/CSharpFindUsagesLSPService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages { [ExportLanguageService(typeof(IFindUsagesLSPService), LanguageNames.CSharp), Shared] internal class CSharpFindUsagesLSPService : AbstractFindUsagesService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindUsagesLSPService() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages { [ExportLanguageService(typeof(IFindUsagesLSPService), LanguageNames.CSharp), Shared] internal class CSharpFindUsagesLSPService : AbstractFindUsagesService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindUsagesLSPService() { } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/OverridesGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverridesGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_Overrides, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken)) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var o in overrides) { var symbolNode = await graphBuilder.AddNodeAsync(o, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, RoslynGraphCategories.Overrides, node, cancellationToken); } } } return graphBuilder; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverridesGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_Overrides, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken)) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var o in overrides) { var symbolNode = await graphBuilder.AddNodeAsync(o, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, RoslynGraphCategories.Overrides, node, cancellationToken); } } } return graphBuilder; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Symbols/Symbol.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.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The base class for all symbols (namespaces, classes, method, parameters, etc.) that are /// exposed by the compiler. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract partial class Symbol : ISymbolInternal, IFormattable { private ISymbol _lazyISymbol; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version of Symbol. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// True if this Symbol should be completed by calling ForceComplete. /// Intuitively, true for source entities (from any compilation). /// </summary> internal virtual bool RequiresCompletion { get { return false; } } internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); } internal virtual bool HasComplete(CompletionPart part) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); return true; } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public virtual string Name { get { return string.Empty; } } /// <summary> /// Gets the name of a symbol as it appears in metadata. Most of the time, this /// is the same as the Name property, with the following exceptions: /// 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that /// indicates the number of type parameters (it does not include, however, names of /// containing types or namespaces). /// 2) The metadata name of explicit interface names have spaces removed, compared to /// the name property. /// </summary> public virtual string MetadataName { get { return this.Name; } } /// <summary> /// Gets the token for this symbol as it appears in metadata. Most of the time this is 0, /// as it is when the symbol is not loaded from metadata. /// </summary> public virtual int MetadataToken => 0; /// <summary> /// Gets the kind of this symbol. /// </summary> public abstract SymbolKind Kind { get; } /// <summary> /// Get the symbol that logically contains this symbol. /// </summary> public abstract Symbol ContainingSymbol { get; } /// <summary> /// Returns the nearest lexically enclosing type, or null if there is none. /// </summary> public virtual NamedTypeSymbol ContainingType { get { Symbol container = this.ContainingSymbol; NamedTypeSymbol containerAsType = container as NamedTypeSymbol; // NOTE: container could be null, so we do not check // whether containerAsType is not null, but // instead check if it did not change after // the cast. if ((object)containerAsType == (object)container) { // this should be relatively uncommon // most symbols that may be contained in a type // know their containing type and can override ContainingType // with a more precise implementation return containerAsType; } // this is recursive, but recursion should be very short // before we reach symbol that definitely knows its containing type. return container.ContainingType; } } /// <summary> /// Gets the nearest enclosing namespace for this namespace or type. For a nested type, /// returns the namespace that contains its container. /// </summary> public virtual NamespaceSymbol ContainingNamespace { get { for (var container = this.ContainingSymbol; (object)container != null; container = container.ContainingSymbol) { var ns = container as NamespaceSymbol; if ((object)ns != null) { return ns; } } return null; } } /// <summary> /// Returns the assembly containing this symbol. If this symbol is shared across multiple /// assemblies, or doesn't belong to an assembly, returns null. /// </summary> public virtual AssemblySymbol ContainingAssembly { get { // Default implementation gets the containers assembly. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingAssembly : null; } } /// <summary> /// For a source assembly, the associated compilation. /// For any other assembly, null. /// For a source module, the DeclaringCompilation of the associated source assembly. /// For any other module, null. /// For any other symbol, the DeclaringCompilation of the associated module. /// </summary> /// <remarks> /// We're going through the containing module, rather than the containing assembly, /// because of /addmodule (symbols in such modules should return null). /// /// Remarks, not "ContainingCompilation" because it isn't transitive. /// </remarks> internal virtual CSharpCompilation DeclaringCompilation { get { switch (this.Kind) { case SymbolKind.ErrorType: return null; case SymbolKind.Assembly: Debug.Assert(!(this is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation"); return null; case SymbolKind.NetModule: Debug.Assert(!(this is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation"); return null; } var sourceModuleSymbol = this.ContainingModule as SourceModuleSymbol; return (object)sourceModuleSymbol == null ? null : sourceModuleSymbol.DeclaringCompilation; } } Compilation ISymbolInternal.DeclaringCompilation => DeclaringCompilation; string ISymbolInternal.Name => this.Name; string ISymbolInternal.MetadataName => this.MetadataName; ISymbolInternal ISymbolInternal.ContainingSymbol => this.ContainingSymbol; IModuleSymbolInternal ISymbolInternal.ContainingModule => this.ContainingModule; IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => this.ContainingAssembly; ImmutableArray<Location> ISymbolInternal.Locations => this.Locations; INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => this.ContainingNamespace; bool ISymbolInternal.IsImplicitlyDeclared => this.IsImplicitlyDeclared; INamedTypeSymbolInternal ISymbolInternal.ContainingType { get { return this.ContainingType; } } ISymbol ISymbolInternal.GetISymbol() => this.ISymbol; /// <summary> /// Returns the module containing this symbol. If this symbol is shared across multiple /// modules, or doesn't belong to a module, returns null. /// </summary> internal virtual ModuleSymbol ContainingModule { get { // Default implementation gets the containers module. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingModule : null; } } /// <summary> /// The index of this member in the containing symbol. This is an optional /// property, implemented by anonymous type properties only, for comparing /// symbols in flow analysis. /// </summary> /// <remarks> /// Should this be used for tuple fields as well? /// </remarks> internal virtual int? MemberIndexOpt => null; /// <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 Symbol OriginalDefinition { get { return OriginalSymbolDefinition; } } protected virtual Symbol OriginalSymbolDefinition { get { return this; } } /// <summary> /// Returns true if this is the original definition of this symbol. /// </summary> public bool IsDefinition { get { return (object)this == (object)OriginalDefinition; } } /// <summary> /// <para> /// Get a source location key for sorting. For performance, it's important that this /// be able to be returned from a symbol without doing any additional allocations (even /// if nothing is cached yet.) /// </para> /// <para> /// Only (original) source symbols and namespaces that can be merged /// need implement this function if they want to do so for efficiency. /// </para> /// </summary> internal virtual LexicalSortKey GetLexicalSortKey() { var locations = this.Locations; var declaringCompilation = this.DeclaringCompilation; Debug.Assert(declaringCompilation != null); // require that it is a source symbol return (locations.Length > 0) ? new LexicalSortKey(locations[0], declaringCompilation) : LexicalSortKey.NotInSource; } /// <summary> /// Gets the locations where this symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public abstract ImmutableArray<Location> Locations { get; } /// <summary> /// <para> /// Get the syntax node(s) where this symbol was declared in source. Some symbols (for /// example, partial classes) may be defined in more than one location. This property should /// return one or more syntax nodes only if the symbol was declared in source code and also /// was not implicitly declared (see the <see cref="IsImplicitlyDeclared"/> property). /// </para> /// <para> /// Note that for namespace symbol, the declaring syntax might be declaring a nested /// namespace. For example, the declaring syntax node for N1 in "namespace N1.N2 {...}" is /// the entire <see cref="BaseNamespaceDeclarationSyntax"/> for N1.N2. For the global namespace, the declaring /// syntax will be the <see cref="CompilationUnitSyntax"/>. /// </para> /// </summary> /// <returns> /// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or /// was implicitly declared, returns an empty read-only array. /// </returns> /// <remarks> /// To go the opposite direction (from syntax node to symbol), see <see /// cref="CSharpSemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>. /// </remarks> public abstract ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get; } /// <summary> /// Helper for implementing <see cref="DeclaringSyntaxReferences"/> for derived classes that store a location but not a /// <see cref="CSharpSyntaxNode"/> or <see cref="SyntaxReference"/>. /// </summary> internal static ImmutableArray<SyntaxReference> GetDeclaringSyntaxReferenceHelper<TNode>(ImmutableArray<Location> locations) where TNode : CSharpSyntaxNode { if (locations.IsEmpty) { return ImmutableArray<SyntaxReference>.Empty; } ArrayBuilder<SyntaxReference> builder = ArrayBuilder<SyntaxReference>.GetInstance(); foreach (Location location in locations) { // Location may be null. See https://github.com/dotnet/roslyn/issues/28862. if (location == null || !location.IsInSource) { continue; } if (location.SourceSpan.Length != 0) { SyntaxToken token = location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start); if (token.Kind() != SyntaxKind.None) { CSharpSyntaxNode node = token.Parent.FirstAncestorOrSelf<TNode>(); if (node != null) { builder.Add(node.GetReference()); } } } else { // Since the location we're interested in can't contain a token, we'll inspect the whole tree, // pruning away branches that don't contain that location. We'll pick the narrowest node of the type // we're looking for. // eg: finding the ParameterSyntax from the empty location of a blank identifier SyntaxNode parent = location.SourceTree.GetRoot(); SyntaxNode found = null; foreach (var descendant in parent.DescendantNodesAndSelf(c => c.Location.SourceSpan.Contains(location.SourceSpan))) { if (descendant is TNode && descendant.Location.SourceSpan.Contains(location.SourceSpan)) { found = descendant; } } if (found is object) { builder.Add(found.GetReference()); } } } return builder.ToImmutableAndFree(); } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns <see cref="Accessibility.NotApplicable"/>. /// </summary> public abstract Accessibility DeclaredAccessibility { get; } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the <c>static</c> modifier or /// implicitly static. /// </summary> public abstract bool IsStatic { get; } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the <c>virtual</c> modifier. Does not return true for /// members declared as abstract or override. /// </summary> public abstract bool IsVirtual { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the <c>override</c> modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> /// <remarks> /// Even for metadata symbols, <see cref="IsOverride"/> = true does not imply that <see cref="IMethodSymbol.OverriddenMethod"/> will /// be non-null. /// </remarks> public abstract bool IsOverride { get; } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the <c>abstract</c> modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public abstract bool IsAbstract { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the <c>sealed</c> modifier. Also set for /// types that do not allow a derived class (declared with <c>sealed</c> or <c>static</c> or <c>struct</c> /// or <c>enum</c> or <c>delegate</c>). /// </summary> public abstract bool IsSealed { get; } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// <c>extern</c> modifier. /// </summary> public abstract bool IsExtern { get; } /// <summary> /// Returns true if this symbol was automatically created by the compiler, and does not /// have an explicit corresponding source code declaration. /// /// This is intended for symbols that are ordinary symbols in the language sense, /// and may be used by code, but that are simply declared implicitly rather than /// with explicit language syntax. /// /// Examples include (this list is not exhaustive): /// the default constructor for a class or struct that is created if one is not provided, /// the BeginInvoke/Invoke/EndInvoke methods for a delegate, /// the generated backing field for an auto property or a field-like event, /// the "this" parameter for non-static methods, /// the "value" parameter for a property setter, /// the parameters on indexer accessor methods (not on the indexer itself), /// methods in anonymous types, /// anonymous functions /// </summary> public virtual bool IsImplicitlyDeclared { get { return false; } } /// <summary> /// Returns true if this symbol can be referenced by its name in code. Examples of symbols /// that cannot be referenced by name are: /// constructors, destructors, operators, explicit interface implementations, /// accessor methods for properties and events, array types. /// </summary> public bool CanBeReferencedByName { get { switch (this.Kind) { case SymbolKind.Local: case SymbolKind.Label: case SymbolKind.Alias: case SymbolKind.RangeVariable: // never imported, and always references by name. return true; case SymbolKind.Namespace: case SymbolKind.Field: case SymbolKind.ErrorType: case SymbolKind.Parameter: case SymbolKind.TypeParameter: case SymbolKind.Event: break; case SymbolKind.NamedType: if (((NamedTypeSymbol)this).IsSubmissionClass) { return false; } break; case SymbolKind.Property: var property = (PropertySymbol)this; if (property.IsIndexer || property.MustCallMethodsDirectly) { return false; } break; case SymbolKind.Method: var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.ReducedExtension: break; case MethodKind.Destructor: // You wouldn't think that destructors would be referenceable by name, but // dev11 only prevents them from being invoked - they can still be assigned // to delegates. return true; case MethodKind.DelegateInvoke: return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: if (!((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly()) { return false; } break; default: return false; } break; case SymbolKind.ArrayType: case SymbolKind.PointerType: case SymbolKind.FunctionPointerType: case SymbolKind.Assembly: case SymbolKind.DynamicType: case SymbolKind.NetModule: case SymbolKind.Discard: return false; default: throw ExceptionUtilities.UnexpectedValue(this.Kind); } // This will eliminate backing fields for auto-props, explicit interface implementations, // indexers, etc. // See the comment on ContainsDroppedIdentifierCharacters for an explanation of why // such names are not referenceable (or see DevDiv #14432). return SyntaxFacts.IsValidIdentifier(this.Name) && !SyntaxFacts.ContainsDroppedIdentifierCharacters(this.Name); } } /// <summary> /// As an optimization, viability checking in the lookup code should use this property instead /// of <see cref="CanBeReferencedByName"/>. The full name check will then be performed in the <see cref="CSharpSemanticModel"/>. /// </summary> /// <remarks> /// This property exists purely for performance reasons. /// </remarks> internal bool CanBeReferencedByNameIgnoringIllegalCharacters { get { if (this.Kind == SymbolKind.Method) { var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.DelegateInvoke: case MethodKind.Destructor: // See comment in CanBeReferencedByName. return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: return ((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly(); default: return false; } } return true; } } /// <summary> /// Perform additional checks after the member has been /// added to the member list of the containing type. /// </summary> internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } // Note: This is no public "IsNew". This is intentional, because new has no syntactic meaning. // It serves only to remove a warning. Furthermore, it can not be inferred from // metadata. For symbols defined in source, the modifiers in the syntax tree // can be examined. /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use <see cref="operator =="/> and <see cref="operator !="/>, or the <see cref="Equals(object)"/> method, to compare two symbols for equality. /// </summary> public static bool operator ==(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // the condition is expected to be folded when inlining "someSymbol == null" if (right is null) { return left is null; } // this part is expected to disappear when inlining "someSymbol == null" return (object)left == (object)right || right.Equals(left); } /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use == and !=, or the Equals method, to compare two symbols for equality. /// </summary> public static bool operator !=(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // //NOTE: we do not implement this as !(left == right) // since that sometimes results in a worse code // the condition is expected to be folded when inlining "someSymbol != null" if (right is null) { return left is object; } // this part is expected to disappear when inlining "someSymbol != null" return (object)left != (object)right && !right.Equals(left); } public sealed override bool Equals(object obj) { return this.Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind); } bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind) { return this.Equals(other as Symbol, compareKind); } // By default we don't consider the compareKind, and do reference equality. This can be overridden. public virtual bool Equals(Symbol other, TypeCompareKind compareKind) { return (object)this == other; } // By default, we do reference equality. This can be overridden. public override int GetHashCode() { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); } public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind) { if (first is null) { return second is null; } return first.Equals(second, compareKind); } /// <summary> /// Returns a string representation of this symbol, suitable for debugging purposes, or /// for placing in an error message. /// </summary> /// <remarks> /// This will provide a useful representation, but it would be clearer to call <see cref="ToDisplayString"/> /// directly and provide an explicit format. /// Sealed so that <see cref="ToString"/> and <see cref="ToDisplayString"/> can't get out of sync. /// </remarks> public sealed override string ToString() { return this.ToDisplayString(); } // ---- End of Public Definition --- // Below here can be various useful virtual methods that are useful to the compiler, but we don't // want to expose publicly. // ---- End of Public Definition --- // Must override this in derived classes for visitor pattern. internal abstract TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a); // Prevent anyone else from deriving from this class. internal Symbol() { } /// <summary> /// Build and add synthesized attributes for this symbol. /// </summary> internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { } /// <summary> /// Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes. /// </summary> internal static void AddSynthesizedAttribute(ref ArrayBuilder<SynthesizedAttributeData> attributes, SynthesizedAttributeData attribute) { if (attribute != null) { if (attributes == null) { attributes = new ArrayBuilder<SynthesizedAttributeData>(1); } attributes.Add(attribute); } } /// <summary> /// <see cref="CharSet"/> effective for this symbol (type or DllImport method). /// Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol. /// </summary> /// <remarks> /// Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </remarks> internal CharSet? GetEffectiveDefaultMarshallingCharSet() { Debug.Assert(this.Kind == SymbolKind.NamedType || this.Kind == SymbolKind.Method); return this.ContainingModule.DefaultMarshallingCharSet; } internal bool IsFromCompilation(CSharpCompilation compilation) { Debug.Assert(compilation != null); return compilation == this.DeclaringCompilation; } /// <summary> /// Always prefer <see cref="IsFromCompilation"/>. /// </summary> /// <remarks> /// <para> /// Unfortunately, when determining overriding/hiding/implementation relationships, we don't /// have the "current" compilation available. We could, but that would clutter up the API /// without providing much benefit. As a compromise, we consider all compilations "current". /// </para> /// <para> /// Unlike in VB, we are not allowing retargeting symbols. This method is used as an approximation /// for <see cref="IsFromCompilation"/> when a compilation is not available and that method will never return /// true for retargeting symbols. /// </para> /// </remarks> internal bool Dangerous_IsFromSomeCompilation { get { return this.DeclaringCompilation != null; } } internal virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { var declaringReferences = this.DeclaringSyntaxReferences; if (this.IsImplicitlyDeclared && declaringReferences.Length == 0) { return this.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var syntaxRef in declaringReferences) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken) { if (locationOpt == null || member.IsDefinedInSourceTree(locationOpt.SourceTree, locationOpt.SourceSpan, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } /// <summary> /// Returns the Documentation Comment ID for the symbol, or null if the symbol doesn't /// support documentation comments. /// </summary> public virtual string GetDocumentationCommentId() { // NOTE: we're using a try-finally here because there's a test that specifically // triggers an exception here to confirm that some symbols don't have documentation // comment IDs. We don't care about "leaks" in such cases, but we don't want spew // in the test output. var pool = PooledStringBuilder.GetInstance(); try { StringBuilder builder = pool.Builder; DocumentationCommentIDVisitor.Instance.Visit(this, builder); return builder.Length == 0 ? null : builder.ToString(); } finally { pool.Free(); } } /// <summary> /// Fetches the documentation comment for this element with a cancellation token. /// </summary> /// <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param> /// <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param> /// <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param> /// <returns>The XML that would be written to the documentation file for the symbol.</returns> public virtual string GetDocumentationCommentXml( CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } private static readonly SymbolDisplayFormat s_debuggerDisplayFormat = SymbolDisplayFormat.TestFormat .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) .WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); internal virtual string GetDebuggerDisplay() { return $"{this.Kind} {this.ToDisplayString(s_debuggerDisplayFormat)}"; } internal virtual void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) { #if DEBUG if (ContainingSymbol is SourceMemberContainerTypeSymbol container) { container.AssertMemberExposure(this, forDiagnostics: true); } #endif if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false || diagnostics.DependenciesBag?.Count > 0) { CSharpCompilation compilation = this.DeclaringCompilation; Debug.Assert(compilation != null); compilation.AddUsedAssemblies(diagnostics.DependenciesBag); if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false) { compilation.DeclarationDiagnostics.AddRange(diagnostics.DiagnosticBag); } } } #region Use-Site Diagnostics /// <summary> /// True if the symbol has a use-site diagnostic with error severity. /// </summary> internal bool HasUseSiteError { get { var info = GetUseSiteInfo(); return info.DiagnosticInfo?.Severity == DiagnosticSeverity.Error; } } /// <summary> /// Returns diagnostic info that should be reported at the use site of the symbol, or default if there is none. /// </summary> internal virtual UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return default; } protected AssemblySymbol PrimaryDependency { get { AssemblySymbol dependency = this.ContainingAssembly; if (dependency is object && dependency.CorLibrary == dependency) { return null; } return dependency; } } /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// Supposed to be ErrorCode, but it causes inconsistent accessibility error. /// </summary> protected virtual int HighestPriorityUseSiteError { get { return int.MaxValue; } } /// <summary> /// Indicates that this symbol uses metadata that cannot be supported by the language. /// /// Examples include: /// - Pointer types in VB /// - ByRef return type /// - Required custom modifiers /// /// This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced. /// Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature. /// /// This is set for metadata symbols, as follows: /// Type - if a type is unsupported (e.g., a pointer type, etc.) /// Method - parameter or return type is unsupported /// Field - type is unsupported /// Event - type is unsupported /// Property - type is unsupported /// Parameter - type is unsupported /// </summary> public virtual bool HasUnsupportedMetadata { get { return false; } } /// <summary> /// Merges given diagnostic to the existing result diagnostic. /// </summary> internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info) { if (info == null) { return false; } if (info.Severity == DiagnosticSeverity.Error && (info.Code == HighestPriorityUseSiteError || HighestPriorityUseSiteError == Int32.MaxValue)) { // this error is final, no other error can override it: result = info; return true; } if (result == null || result.Severity == DiagnosticSeverity.Warning && info.Severity == DiagnosticSeverity.Error) { // there could be an error of higher-priority result = info; return false; } // we have a second low-pri error, continue looking for a higher priority one return false; } /// <summary> /// Merges given diagnostic and dependencies to the existing result. /// </summary> internal bool MergeUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result, UseSiteInfo<AssemblySymbol> info) { DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; bool retVal = MergeUseSiteDiagnostics(ref diagnosticInfo, info.DiagnosticInfo); if (diagnosticInfo?.Severity == DiagnosticSeverity.Error) { result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo); return retVal; } var secondaryDependencies = result.SecondaryDependencies; var primaryDependency = result.PrimaryDependency; info.MergeDependencies(ref primaryDependency, ref secondaryDependencies); result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo, primaryDependency, secondaryDependencies); Debug.Assert(!retVal); return retVal; } /// <summary> /// Reports specified use-site diagnostic to given diagnostic bag. /// </summary> /// <remarks> /// This method should be the only method adding use-site diagnostics to a diagnostic bag. /// It performs additional adjustments of the location for unification related diagnostics and /// may be the place where to add more use-site location post-processing. /// </remarks> /// <returns>True if the diagnostic has error severity.</returns> internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location) { // Unlike VB the C# Dev11 compiler reports only a single unification error/warning. // By dropping the location we effectively merge all unification use-site errors that have the same error code into a single error. // The error message clearly explains how to fix the problem and reporting the error for each location wouldn't add much value. if (info.Code == (int)ErrorCode.WRN_UnifyReferenceBldRev || info.Code == (int)ErrorCode.WRN_UnifyReferenceMajMin || info.Code == (int)ErrorCode.ERR_AssemblyMatchBadVersion) { location = NoLocation.Singleton; } diagnostics.Add(info, location); return info.Severity == DiagnosticSeverity.Error; } internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSiteDiagnostic(info, location); } /// <summary> /// Derive use-site info from a type symbol. /// </summary> internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeSymbol type) { UseSiteInfo<AssemblySymbol> info = type.GetUseSiteInfo(); if (info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType) { GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info); } return MergeUseSiteInfo(ref result, info); } private void GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref UseSiteInfo<AssemblySymbol> info) { switch (this.Kind) { case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: info = info.AdjustDiagnosticInfo(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); break; } } private UseSiteInfo<AssemblySymbol> GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() { var useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty)); GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref useSiteInfo); return useSiteInfo; } internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType) { return DeriveUseSiteInfoFromType(ref result, type.Type) || DeriveUseSiteInfoFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType); } internal bool DeriveUseSiteInfoFromParameter(ref UseSiteInfo<AssemblySymbol> result, ParameterSymbol param) { return DeriveUseSiteInfoFromType(ref result, param.TypeWithAnnotations, AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, param.RefCustomModifiers, this is MethodSymbol method && method.MethodKind == MethodKind.FunctionPointerSignature ? AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute | AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute : AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute); } internal bool DeriveUseSiteInfoFromParameters(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<ParameterSymbol> parameters) { foreach (ParameterSymbol param in parameters) { if (DeriveUseSiteInfoFromParameter(ref result, param)) { return true; } } return false; } [Flags] internal enum AllowedRequiredModifierType { None = 0, System_Runtime_CompilerServices_Volatile = 1, System_Runtime_InteropServices_InAttribute = 1 << 1, System_Runtime_CompilerServices_IsExternalInit = 1 << 2, System_Runtime_CompilerServices_OutAttribute = 1 << 3, } internal bool DeriveUseSiteInfoFromCustomModifiers(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<CustomModifier> customModifiers, AllowedRequiredModifierType allowedRequiredModifierType) { AllowedRequiredModifierType requiredModifiersFound = AllowedRequiredModifierType.None; bool checkRequiredModifiers = true; foreach (CustomModifier modifier in customModifiers) { NamedTypeSymbol modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; if (checkRequiredModifiers && !modifier.IsOptional) { AllowedRequiredModifierType current = AllowedRequiredModifierType.None; if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) != 0 && modifierType.IsWellKnownTypeInAttribute()) { current = AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile) != 0 && modifierType.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit) != 0 && modifierType.IsWellKnownTypeIsExternalInit()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) != 0 && modifierType.IsWellKnownTypeOutAttribute()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute; } if (current == AllowedRequiredModifierType.None || (current != requiredModifiersFound && requiredModifiersFound != AllowedRequiredModifierType.None)) // At the moment we don't support applying different allowed modreqs to the same target. { if (MergeUseSiteInfo(ref result, GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo())) { return true; } checkRequiredModifiers = false; } requiredModifiersFound |= current; } // Unbound generic type is valid as a modifier, let's not report any use site diagnostics because of that. if (modifierType.IsUnboundGenericType) { modifierType = modifierType.OriginalDefinition; } if (DeriveUseSiteInfoFromType(ref result, modifierType)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive<T>(ref DiagnosticInfo result, ImmutableArray<T> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) where T : TypeSymbol { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeWithAnnotations> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<CustomModifier> modifiers, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var modifier in modifiers) { if (((CSharpCustomModifier)modifier).ModifierSymbol.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<ParameterSymbol> parameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, parameter.RefCustomModifiers, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeParameterSymbol> typeParameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var typeParameter in typeParameters) { if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeParameter.ConstraintTypesNoUseSiteDiagnostics, owner, ref checkedTypes)) { return true; } } return false; } #endregion /// <summary> /// True if this symbol has been marked with the <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="ThreeState.Unknown"/> if the <see cref="ObsoleteAttribute"/> attribute hasn't been cracked yet. /// </summary> internal ThreeState ObsoleteState { get { switch (ObsoleteKind) { case ObsoleteAttributeKind.None: case ObsoleteAttributeKind.Experimental: return ThreeState.False; case ObsoleteAttributeKind.Uninitialized: return ThreeState.Unknown; default: return ThreeState.True; } } } internal ObsoleteAttributeKind ObsoleteKind { get { var data = this.ObsoleteAttributeData; return (data == null) ? ObsoleteAttributeKind.None : data.Kind; } } /// <summary> /// Returns data decoded from <see cref="ObsoleteAttribute"/> attribute or null if there is no <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="Microsoft.CodeAnalysis.ObsoleteAttributeData.Uninitialized"/> if attribute arguments haven't been decoded yet. /// </summary> internal abstract ObsoleteAttributeData ObsoleteAttributeData { get; } /// <summary> /// Returns true and a <see cref="string"/> from the first <see cref="GuidAttribute"/> on the symbol, /// the string might be null or an invalid guid representation. False, /// if there is no <see cref="GuidAttribute"/> with string argument. /// </summary> internal bool GetGuidStringDefaultImplementation(out string guidString) { foreach (var attrData in this.GetAttributes()) { if (attrData.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { if (attrData.TryGetGuidAttributeValue(out guidString)) { return true; } } } guidString = null; return false; } public string ToDisplayString(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString(ISymbol, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts(ISymbol, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString(ISymbol, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts(ISymbol, semanticModel, position, format); } internal static void ReportErrorIfHasConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, DiagnosticBag diagnostics) { if (constraintClauses.Count > 0) { diagnostics.Add( ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, constraintClauses[0].WhereKeyword.GetLocation()); } } internal static void CheckForBlockAndExpressionBody( CSharpSyntaxNode block, CSharpSyntaxNode expression, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { if (block != null && expression != null) { diagnostics.Add(ErrorCode.ERR_BlockBodyAndExpressionBody, syntax.GetLocation()); } } [Flags] internal enum ReservedAttributes { DynamicAttribute = 1 << 1, IsReadOnlyAttribute = 1 << 2, IsUnmanagedAttribute = 1 << 3, IsByRefLikeAttribute = 1 << 4, TupleElementNamesAttribute = 1 << 5, NullableAttribute = 1 << 6, NullableContextAttribute = 1 << 7, NullablePublicOnlyAttribute = 1 << 8, NativeIntegerAttribute = 1 << 9, CaseSensitiveExtensionAttribute = 1 << 10, } internal bool ReportExplicitUseOfReservedAttributes(in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, ReservedAttributes reserved) { var attribute = arguments.Attribute; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if ((reserved & ReservedAttributes.DynamicAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute)) { // DynamicAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.IsReadOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsReadOnlyAttribute)) { } else if ((reserved & ReservedAttributes.IsUnmanagedAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsUnmanagedAttribute)) { } else if ((reserved & ReservedAttributes.IsByRefLikeAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsByRefLikeAttribute)) { } else if ((reserved & ReservedAttributes.TupleElementNamesAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute)) { diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableContextAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullableContextAttribute)) { } else if ((reserved & ReservedAttributes.NullablePublicOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullablePublicOnlyAttribute)) { } else if ((reserved & ReservedAttributes.NativeIntegerAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NativeIntegerAttribute)) { } else if ((reserved & ReservedAttributes.CaseSensitiveExtensionAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) { // ExtensionAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location); } else { return false; } return true; bool reportExplicitUseOfReservedAttribute(CSharpAttributeData attribute, in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, in AttributeDescription attributeDescription) { if (attribute.IsTargetAttribute(this, attributeDescription)) { // Do not use '{FullName}'. This is reserved for compiler usage. diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, attributeDescription.FullName); return true; } return false; } } internal virtual byte? GetNullableContextValue() { return GetLocalNullableContextValue() ?? ContainingSymbol?.GetNullableContextValue(); } internal virtual byte? GetLocalNullableContextValue() { return null; } internal void GetCommonNullableValues(CSharpCompilation compilation, ref MostCommonNullableValueBuilder builder) { switch (this.Kind) { case SymbolKind.NamedType: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Event: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((EventSymbol)this).TypeWithAnnotations); } break; case SymbolKind.Field: var field = (FieldSymbol)this; if (field is TupleElementFieldSymbol tupleElement) { field = tupleElement.TupleUnderlyingField; } if (compilation.ShouldEmitNullableAttributes(field)) { builder.AddValue(field.TypeWithAnnotations); } break; case SymbolKind.Method: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Property: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((PropertySymbol)this).TypeWithAnnotations); // Attributes are not emitted for property parameters. } break; case SymbolKind.Parameter: builder.AddValue(((ParameterSymbol)this).TypeWithAnnotations); break; case SymbolKind.TypeParameter: if (this is SourceTypeParameterSymbolBase typeParameter) { builder.AddValue(typeParameter.GetSynthesizedNullableAttributeValue()); foreach (var constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics) { builder.AddValue(constraintType); } } break; } } internal bool ShouldEmitNullableContextValue(out byte value) { byte? localValue = GetLocalNullableContextValue(); if (localValue == null) { value = 0; return false; } value = localValue.GetValueOrDefault(); byte containingValue = ContainingSymbol?.GetNullableContextValue() ?? 0; return value != containingValue; } /// <summary> /// True if the symbol is declared outside of the scope of the containing /// symbol /// </summary> internal static bool IsCaptured(Symbol variable, SourceMethodSymbol containingSymbol) { switch (variable.Kind) { case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: // Range variables are not captured, but their underlying parameters // may be. If this is a range underlying parameter it will be a // ParameterSymbol, not a RangeVariableSymbol. case SymbolKind.RangeVariable: return false; case SymbolKind.Local: if (((LocalSymbol)variable).IsConst) { return false; } break; case SymbolKind.Parameter: break; case SymbolKind.Method: if (variable is LocalFunctionSymbol localFunction) { // calling a static local function doesn't require capturing state if (localFunction.IsStatic) { return false; } break; } throw ExceptionUtilities.UnexpectedValue(variable); default: throw ExceptionUtilities.UnexpectedValue(variable.Kind); } // Walk up the containing symbols until we find the target function, in which // case the variable is not captured by the target function, or null, in which // case it is. for (var currentFunction = variable.ContainingSymbol; (object)currentFunction != null; currentFunction = currentFunction.ContainingSymbol) { if (ReferenceEquals(currentFunction, containingSymbol)) { return false; } } return true; } bool ISymbolInternal.IsStatic { get { return this.IsStatic; } } bool ISymbolInternal.IsVirtual { get { return this.IsVirtual; } } bool ISymbolInternal.IsOverride { get { return this.IsOverride; } } bool ISymbolInternal.IsAbstract { get { return this.IsAbstract; } } Accessibility ISymbolInternal.DeclaredAccessibility { get { return this.DeclaredAccessibility; } } public abstract void Accept(CSharpSymbolVisitor visitor); public abstract TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor); string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } protected abstract ISymbol CreateISymbol(); internal ISymbol ISymbol { get { if (_lazyISymbol is null) { Interlocked.CompareExchange(ref _lazyISymbol, CreateISymbol(), null); } return _lazyISymbol; } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The base class for all symbols (namespaces, classes, method, parameters, etc.) that are /// exposed by the compiler. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract partial class Symbol : ISymbolInternal, IFormattable { private ISymbol _lazyISymbol; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version of Symbol. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// True if this Symbol should be completed by calling ForceComplete. /// Intuitively, true for source entities (from any compilation). /// </summary> internal virtual bool RequiresCompletion { get { return false; } } internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); } internal virtual bool HasComplete(CompletionPart part) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); return true; } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public virtual string Name { get { return string.Empty; } } /// <summary> /// Gets the name of a symbol as it appears in metadata. Most of the time, this /// is the same as the Name property, with the following exceptions: /// 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that /// indicates the number of type parameters (it does not include, however, names of /// containing types or namespaces). /// 2) The metadata name of explicit interface names have spaces removed, compared to /// the name property. /// </summary> public virtual string MetadataName { get { return this.Name; } } /// <summary> /// Gets the token for this symbol as it appears in metadata. Most of the time this is 0, /// as it is when the symbol is not loaded from metadata. /// </summary> public virtual int MetadataToken => 0; /// <summary> /// Gets the kind of this symbol. /// </summary> public abstract SymbolKind Kind { get; } /// <summary> /// Get the symbol that logically contains this symbol. /// </summary> public abstract Symbol ContainingSymbol { get; } /// <summary> /// Returns the nearest lexically enclosing type, or null if there is none. /// </summary> public virtual NamedTypeSymbol ContainingType { get { Symbol container = this.ContainingSymbol; NamedTypeSymbol containerAsType = container as NamedTypeSymbol; // NOTE: container could be null, so we do not check // whether containerAsType is not null, but // instead check if it did not change after // the cast. if ((object)containerAsType == (object)container) { // this should be relatively uncommon // most symbols that may be contained in a type // know their containing type and can override ContainingType // with a more precise implementation return containerAsType; } // this is recursive, but recursion should be very short // before we reach symbol that definitely knows its containing type. return container.ContainingType; } } /// <summary> /// Gets the nearest enclosing namespace for this namespace or type. For a nested type, /// returns the namespace that contains its container. /// </summary> public virtual NamespaceSymbol ContainingNamespace { get { for (var container = this.ContainingSymbol; (object)container != null; container = container.ContainingSymbol) { var ns = container as NamespaceSymbol; if ((object)ns != null) { return ns; } } return null; } } /// <summary> /// Returns the assembly containing this symbol. If this symbol is shared across multiple /// assemblies, or doesn't belong to an assembly, returns null. /// </summary> public virtual AssemblySymbol ContainingAssembly { get { // Default implementation gets the containers assembly. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingAssembly : null; } } /// <summary> /// For a source assembly, the associated compilation. /// For any other assembly, null. /// For a source module, the DeclaringCompilation of the associated source assembly. /// For any other module, null. /// For any other symbol, the DeclaringCompilation of the associated module. /// </summary> /// <remarks> /// We're going through the containing module, rather than the containing assembly, /// because of /addmodule (symbols in such modules should return null). /// /// Remarks, not "ContainingCompilation" because it isn't transitive. /// </remarks> internal virtual CSharpCompilation DeclaringCompilation { get { switch (this.Kind) { case SymbolKind.ErrorType: return null; case SymbolKind.Assembly: Debug.Assert(!(this is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation"); return null; case SymbolKind.NetModule: Debug.Assert(!(this is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation"); return null; } var sourceModuleSymbol = this.ContainingModule as SourceModuleSymbol; return (object)sourceModuleSymbol == null ? null : sourceModuleSymbol.DeclaringCompilation; } } Compilation ISymbolInternal.DeclaringCompilation => DeclaringCompilation; string ISymbolInternal.Name => this.Name; string ISymbolInternal.MetadataName => this.MetadataName; ISymbolInternal ISymbolInternal.ContainingSymbol => this.ContainingSymbol; IModuleSymbolInternal ISymbolInternal.ContainingModule => this.ContainingModule; IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => this.ContainingAssembly; ImmutableArray<Location> ISymbolInternal.Locations => this.Locations; INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => this.ContainingNamespace; bool ISymbolInternal.IsImplicitlyDeclared => this.IsImplicitlyDeclared; INamedTypeSymbolInternal ISymbolInternal.ContainingType { get { return this.ContainingType; } } ISymbol ISymbolInternal.GetISymbol() => this.ISymbol; /// <summary> /// Returns the module containing this symbol. If this symbol is shared across multiple /// modules, or doesn't belong to a module, returns null. /// </summary> internal virtual ModuleSymbol ContainingModule { get { // Default implementation gets the containers module. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingModule : null; } } /// <summary> /// The index of this member in the containing symbol. This is an optional /// property, implemented by anonymous type properties only, for comparing /// symbols in flow analysis. /// </summary> /// <remarks> /// Should this be used for tuple fields as well? /// </remarks> internal virtual int? MemberIndexOpt => null; /// <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 Symbol OriginalDefinition { get { return OriginalSymbolDefinition; } } protected virtual Symbol OriginalSymbolDefinition { get { return this; } } /// <summary> /// Returns true if this is the original definition of this symbol. /// </summary> public bool IsDefinition { get { return (object)this == (object)OriginalDefinition; } } /// <summary> /// <para> /// Get a source location key for sorting. For performance, it's important that this /// be able to be returned from a symbol without doing any additional allocations (even /// if nothing is cached yet.) /// </para> /// <para> /// Only (original) source symbols and namespaces that can be merged /// need implement this function if they want to do so for efficiency. /// </para> /// </summary> internal virtual LexicalSortKey GetLexicalSortKey() { var locations = this.Locations; var declaringCompilation = this.DeclaringCompilation; Debug.Assert(declaringCompilation != null); // require that it is a source symbol return (locations.Length > 0) ? new LexicalSortKey(locations[0], declaringCompilation) : LexicalSortKey.NotInSource; } /// <summary> /// Gets the locations where this symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public abstract ImmutableArray<Location> Locations { get; } /// <summary> /// <para> /// Get the syntax node(s) where this symbol was declared in source. Some symbols (for /// example, partial classes) may be defined in more than one location. This property should /// return one or more syntax nodes only if the symbol was declared in source code and also /// was not implicitly declared (see the <see cref="IsImplicitlyDeclared"/> property). /// </para> /// <para> /// Note that for namespace symbol, the declaring syntax might be declaring a nested /// namespace. For example, the declaring syntax node for N1 in "namespace N1.N2 {...}" is /// the entire <see cref="BaseNamespaceDeclarationSyntax"/> for N1.N2. For the global namespace, the declaring /// syntax will be the <see cref="CompilationUnitSyntax"/>. /// </para> /// </summary> /// <returns> /// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or /// was implicitly declared, returns an empty read-only array. /// </returns> /// <remarks> /// To go the opposite direction (from syntax node to symbol), see <see /// cref="CSharpSemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>. /// </remarks> public abstract ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get; } /// <summary> /// Helper for implementing <see cref="DeclaringSyntaxReferences"/> for derived classes that store a location but not a /// <see cref="CSharpSyntaxNode"/> or <see cref="SyntaxReference"/>. /// </summary> internal static ImmutableArray<SyntaxReference> GetDeclaringSyntaxReferenceHelper<TNode>(ImmutableArray<Location> locations) where TNode : CSharpSyntaxNode { if (locations.IsEmpty) { return ImmutableArray<SyntaxReference>.Empty; } ArrayBuilder<SyntaxReference> builder = ArrayBuilder<SyntaxReference>.GetInstance(); foreach (Location location in locations) { // Location may be null. See https://github.com/dotnet/roslyn/issues/28862. if (location == null || !location.IsInSource) { continue; } if (location.SourceSpan.Length != 0) { SyntaxToken token = location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start); if (token.Kind() != SyntaxKind.None) { CSharpSyntaxNode node = token.Parent.FirstAncestorOrSelf<TNode>(); if (node != null) { builder.Add(node.GetReference()); } } } else { // Since the location we're interested in can't contain a token, we'll inspect the whole tree, // pruning away branches that don't contain that location. We'll pick the narrowest node of the type // we're looking for. // eg: finding the ParameterSyntax from the empty location of a blank identifier SyntaxNode parent = location.SourceTree.GetRoot(); SyntaxNode found = null; foreach (var descendant in parent.DescendantNodesAndSelf(c => c.Location.SourceSpan.Contains(location.SourceSpan))) { if (descendant is TNode && descendant.Location.SourceSpan.Contains(location.SourceSpan)) { found = descendant; } } if (found is object) { builder.Add(found.GetReference()); } } } return builder.ToImmutableAndFree(); } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns <see cref="Accessibility.NotApplicable"/>. /// </summary> public abstract Accessibility DeclaredAccessibility { get; } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the <c>static</c> modifier or /// implicitly static. /// </summary> public abstract bool IsStatic { get; } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the <c>virtual</c> modifier. Does not return true for /// members declared as abstract or override. /// </summary> public abstract bool IsVirtual { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the <c>override</c> modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> /// <remarks> /// Even for metadata symbols, <see cref="IsOverride"/> = true does not imply that <see cref="IMethodSymbol.OverriddenMethod"/> will /// be non-null. /// </remarks> public abstract bool IsOverride { get; } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the <c>abstract</c> modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public abstract bool IsAbstract { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the <c>sealed</c> modifier. Also set for /// types that do not allow a derived class (declared with <c>sealed</c> or <c>static</c> or <c>struct</c> /// or <c>enum</c> or <c>delegate</c>). /// </summary> public abstract bool IsSealed { get; } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// <c>extern</c> modifier. /// </summary> public abstract bool IsExtern { get; } /// <summary> /// Returns true if this symbol was automatically created by the compiler, and does not /// have an explicit corresponding source code declaration. /// /// This is intended for symbols that are ordinary symbols in the language sense, /// and may be used by code, but that are simply declared implicitly rather than /// with explicit language syntax. /// /// Examples include (this list is not exhaustive): /// the default constructor for a class or struct that is created if one is not provided, /// the BeginInvoke/Invoke/EndInvoke methods for a delegate, /// the generated backing field for an auto property or a field-like event, /// the "this" parameter for non-static methods, /// the "value" parameter for a property setter, /// the parameters on indexer accessor methods (not on the indexer itself), /// methods in anonymous types, /// anonymous functions /// </summary> public virtual bool IsImplicitlyDeclared { get { return false; } } /// <summary> /// Returns true if this symbol can be referenced by its name in code. Examples of symbols /// that cannot be referenced by name are: /// constructors, destructors, operators, explicit interface implementations, /// accessor methods for properties and events, array types. /// </summary> public bool CanBeReferencedByName { get { switch (this.Kind) { case SymbolKind.Local: case SymbolKind.Label: case SymbolKind.Alias: case SymbolKind.RangeVariable: // never imported, and always references by name. return true; case SymbolKind.Namespace: case SymbolKind.Field: case SymbolKind.ErrorType: case SymbolKind.Parameter: case SymbolKind.TypeParameter: case SymbolKind.Event: break; case SymbolKind.NamedType: if (((NamedTypeSymbol)this).IsSubmissionClass) { return false; } break; case SymbolKind.Property: var property = (PropertySymbol)this; if (property.IsIndexer || property.MustCallMethodsDirectly) { return false; } break; case SymbolKind.Method: var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.ReducedExtension: break; case MethodKind.Destructor: // You wouldn't think that destructors would be referenceable by name, but // dev11 only prevents them from being invoked - they can still be assigned // to delegates. return true; case MethodKind.DelegateInvoke: return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: if (!((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly()) { return false; } break; default: return false; } break; case SymbolKind.ArrayType: case SymbolKind.PointerType: case SymbolKind.FunctionPointerType: case SymbolKind.Assembly: case SymbolKind.DynamicType: case SymbolKind.NetModule: case SymbolKind.Discard: return false; default: throw ExceptionUtilities.UnexpectedValue(this.Kind); } // This will eliminate backing fields for auto-props, explicit interface implementations, // indexers, etc. // See the comment on ContainsDroppedIdentifierCharacters for an explanation of why // such names are not referenceable (or see DevDiv #14432). return SyntaxFacts.IsValidIdentifier(this.Name) && !SyntaxFacts.ContainsDroppedIdentifierCharacters(this.Name); } } /// <summary> /// As an optimization, viability checking in the lookup code should use this property instead /// of <see cref="CanBeReferencedByName"/>. The full name check will then be performed in the <see cref="CSharpSemanticModel"/>. /// </summary> /// <remarks> /// This property exists purely for performance reasons. /// </remarks> internal bool CanBeReferencedByNameIgnoringIllegalCharacters { get { if (this.Kind == SymbolKind.Method) { var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.DelegateInvoke: case MethodKind.Destructor: // See comment in CanBeReferencedByName. return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: return ((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly(); default: return false; } } return true; } } /// <summary> /// Perform additional checks after the member has been /// added to the member list of the containing type. /// </summary> internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } // Note: This is no public "IsNew". This is intentional, because new has no syntactic meaning. // It serves only to remove a warning. Furthermore, it can not be inferred from // metadata. For symbols defined in source, the modifiers in the syntax tree // can be examined. /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use <see cref="operator =="/> and <see cref="operator !="/>, or the <see cref="Equals(object)"/> method, to compare two symbols for equality. /// </summary> public static bool operator ==(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // the condition is expected to be folded when inlining "someSymbol == null" if (right is null) { return left is null; } // this part is expected to disappear when inlining "someSymbol == null" return (object)left == (object)right || right.Equals(left); } /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use == and !=, or the Equals method, to compare two symbols for equality. /// </summary> public static bool operator !=(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // //NOTE: we do not implement this as !(left == right) // since that sometimes results in a worse code // the condition is expected to be folded when inlining "someSymbol != null" if (right is null) { return left is object; } // this part is expected to disappear when inlining "someSymbol != null" return (object)left != (object)right && !right.Equals(left); } public sealed override bool Equals(object obj) { return this.Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind); } bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind) { return this.Equals(other as Symbol, compareKind); } // By default we don't consider the compareKind, and do reference equality. This can be overridden. public virtual bool Equals(Symbol other, TypeCompareKind compareKind) { return (object)this == other; } // By default, we do reference equality. This can be overridden. public override int GetHashCode() { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); } public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind) { if (first is null) { return second is null; } return first.Equals(second, compareKind); } /// <summary> /// Returns a string representation of this symbol, suitable for debugging purposes, or /// for placing in an error message. /// </summary> /// <remarks> /// This will provide a useful representation, but it would be clearer to call <see cref="ToDisplayString"/> /// directly and provide an explicit format. /// Sealed so that <see cref="ToString"/> and <see cref="ToDisplayString"/> can't get out of sync. /// </remarks> public sealed override string ToString() { return this.ToDisplayString(); } // ---- End of Public Definition --- // Below here can be various useful virtual methods that are useful to the compiler, but we don't // want to expose publicly. // ---- End of Public Definition --- // Must override this in derived classes for visitor pattern. internal abstract TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a); // Prevent anyone else from deriving from this class. internal Symbol() { } /// <summary> /// Build and add synthesized attributes for this symbol. /// </summary> internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { } /// <summary> /// Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes. /// </summary> internal static void AddSynthesizedAttribute(ref ArrayBuilder<SynthesizedAttributeData> attributes, SynthesizedAttributeData attribute) { if (attribute != null) { if (attributes == null) { attributes = new ArrayBuilder<SynthesizedAttributeData>(1); } attributes.Add(attribute); } } /// <summary> /// <see cref="CharSet"/> effective for this symbol (type or DllImport method). /// Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol. /// </summary> /// <remarks> /// Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </remarks> internal CharSet? GetEffectiveDefaultMarshallingCharSet() { Debug.Assert(this.Kind == SymbolKind.NamedType || this.Kind == SymbolKind.Method); return this.ContainingModule.DefaultMarshallingCharSet; } internal bool IsFromCompilation(CSharpCompilation compilation) { Debug.Assert(compilation != null); return compilation == this.DeclaringCompilation; } /// <summary> /// Always prefer <see cref="IsFromCompilation"/>. /// </summary> /// <remarks> /// <para> /// Unfortunately, when determining overriding/hiding/implementation relationships, we don't /// have the "current" compilation available. We could, but that would clutter up the API /// without providing much benefit. As a compromise, we consider all compilations "current". /// </para> /// <para> /// Unlike in VB, we are not allowing retargeting symbols. This method is used as an approximation /// for <see cref="IsFromCompilation"/> when a compilation is not available and that method will never return /// true for retargeting symbols. /// </para> /// </remarks> internal bool Dangerous_IsFromSomeCompilation { get { return this.DeclaringCompilation != null; } } internal virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { var declaringReferences = this.DeclaringSyntaxReferences; if (this.IsImplicitlyDeclared && declaringReferences.Length == 0) { return this.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var syntaxRef in declaringReferences) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken) { if (locationOpt == null || member.IsDefinedInSourceTree(locationOpt.SourceTree, locationOpt.SourceSpan, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } /// <summary> /// Returns the Documentation Comment ID for the symbol, or null if the symbol doesn't /// support documentation comments. /// </summary> public virtual string GetDocumentationCommentId() { // NOTE: we're using a try-finally here because there's a test that specifically // triggers an exception here to confirm that some symbols don't have documentation // comment IDs. We don't care about "leaks" in such cases, but we don't want spew // in the test output. var pool = PooledStringBuilder.GetInstance(); try { StringBuilder builder = pool.Builder; DocumentationCommentIDVisitor.Instance.Visit(this, builder); return builder.Length == 0 ? null : builder.ToString(); } finally { pool.Free(); } } /// <summary> /// Fetches the documentation comment for this element with a cancellation token. /// </summary> /// <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param> /// <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param> /// <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param> /// <returns>The XML that would be written to the documentation file for the symbol.</returns> public virtual string GetDocumentationCommentXml( CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } private static readonly SymbolDisplayFormat s_debuggerDisplayFormat = SymbolDisplayFormat.TestFormat .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) .WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); internal virtual string GetDebuggerDisplay() { return $"{this.Kind} {this.ToDisplayString(s_debuggerDisplayFormat)}"; } internal virtual void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) { #if DEBUG if (ContainingSymbol is SourceMemberContainerTypeSymbol container) { container.AssertMemberExposure(this, forDiagnostics: true); } #endif if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false || diagnostics.DependenciesBag?.Count > 0) { CSharpCompilation compilation = this.DeclaringCompilation; Debug.Assert(compilation != null); compilation.AddUsedAssemblies(diagnostics.DependenciesBag); if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false) { compilation.DeclarationDiagnostics.AddRange(diagnostics.DiagnosticBag); } } } #region Use-Site Diagnostics /// <summary> /// True if the symbol has a use-site diagnostic with error severity. /// </summary> internal bool HasUseSiteError { get { var info = GetUseSiteInfo(); return info.DiagnosticInfo?.Severity == DiagnosticSeverity.Error; } } /// <summary> /// Returns diagnostic info that should be reported at the use site of the symbol, or default if there is none. /// </summary> internal virtual UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return default; } protected AssemblySymbol PrimaryDependency { get { AssemblySymbol dependency = this.ContainingAssembly; if (dependency is object && dependency.CorLibrary == dependency) { return null; } return dependency; } } /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// Supposed to be ErrorCode, but it causes inconsistent accessibility error. /// </summary> protected virtual int HighestPriorityUseSiteError { get { return int.MaxValue; } } /// <summary> /// Indicates that this symbol uses metadata that cannot be supported by the language. /// /// Examples include: /// - Pointer types in VB /// - ByRef return type /// - Required custom modifiers /// /// This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced. /// Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature. /// /// This is set for metadata symbols, as follows: /// Type - if a type is unsupported (e.g., a pointer type, etc.) /// Method - parameter or return type is unsupported /// Field - type is unsupported /// Event - type is unsupported /// Property - type is unsupported /// Parameter - type is unsupported /// </summary> public virtual bool HasUnsupportedMetadata { get { return false; } } /// <summary> /// Merges given diagnostic to the existing result diagnostic. /// </summary> internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info) { if (info == null) { return false; } if (info.Severity == DiagnosticSeverity.Error && (info.Code == HighestPriorityUseSiteError || HighestPriorityUseSiteError == Int32.MaxValue)) { // this error is final, no other error can override it: result = info; return true; } if (result == null || result.Severity == DiagnosticSeverity.Warning && info.Severity == DiagnosticSeverity.Error) { // there could be an error of higher-priority result = info; return false; } // we have a second low-pri error, continue looking for a higher priority one return false; } /// <summary> /// Merges given diagnostic and dependencies to the existing result. /// </summary> internal bool MergeUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result, UseSiteInfo<AssemblySymbol> info) { DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; bool retVal = MergeUseSiteDiagnostics(ref diagnosticInfo, info.DiagnosticInfo); if (diagnosticInfo?.Severity == DiagnosticSeverity.Error) { result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo); return retVal; } var secondaryDependencies = result.SecondaryDependencies; var primaryDependency = result.PrimaryDependency; info.MergeDependencies(ref primaryDependency, ref secondaryDependencies); result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo, primaryDependency, secondaryDependencies); Debug.Assert(!retVal); return retVal; } /// <summary> /// Reports specified use-site diagnostic to given diagnostic bag. /// </summary> /// <remarks> /// This method should be the only method adding use-site diagnostics to a diagnostic bag. /// It performs additional adjustments of the location for unification related diagnostics and /// may be the place where to add more use-site location post-processing. /// </remarks> /// <returns>True if the diagnostic has error severity.</returns> internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location) { // Unlike VB the C# Dev11 compiler reports only a single unification error/warning. // By dropping the location we effectively merge all unification use-site errors that have the same error code into a single error. // The error message clearly explains how to fix the problem and reporting the error for each location wouldn't add much value. if (info.Code == (int)ErrorCode.WRN_UnifyReferenceBldRev || info.Code == (int)ErrorCode.WRN_UnifyReferenceMajMin || info.Code == (int)ErrorCode.ERR_AssemblyMatchBadVersion) { location = NoLocation.Singleton; } diagnostics.Add(info, location); return info.Severity == DiagnosticSeverity.Error; } internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSiteDiagnostic(info, location); } /// <summary> /// Derive use-site info from a type symbol. /// </summary> internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeSymbol type) { UseSiteInfo<AssemblySymbol> info = type.GetUseSiteInfo(); if (info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType) { GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info); } return MergeUseSiteInfo(ref result, info); } private void GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref UseSiteInfo<AssemblySymbol> info) { switch (this.Kind) { case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: info = info.AdjustDiagnosticInfo(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); break; } } private UseSiteInfo<AssemblySymbol> GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() { var useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty)); GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref useSiteInfo); return useSiteInfo; } internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType) { return DeriveUseSiteInfoFromType(ref result, type.Type) || DeriveUseSiteInfoFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType); } internal bool DeriveUseSiteInfoFromParameter(ref UseSiteInfo<AssemblySymbol> result, ParameterSymbol param) { return DeriveUseSiteInfoFromType(ref result, param.TypeWithAnnotations, AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, param.RefCustomModifiers, this is MethodSymbol method && method.MethodKind == MethodKind.FunctionPointerSignature ? AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute | AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute : AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute); } internal bool DeriveUseSiteInfoFromParameters(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<ParameterSymbol> parameters) { foreach (ParameterSymbol param in parameters) { if (DeriveUseSiteInfoFromParameter(ref result, param)) { return true; } } return false; } [Flags] internal enum AllowedRequiredModifierType { None = 0, System_Runtime_CompilerServices_Volatile = 1, System_Runtime_InteropServices_InAttribute = 1 << 1, System_Runtime_CompilerServices_IsExternalInit = 1 << 2, System_Runtime_CompilerServices_OutAttribute = 1 << 3, } internal bool DeriveUseSiteInfoFromCustomModifiers(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<CustomModifier> customModifiers, AllowedRequiredModifierType allowedRequiredModifierType) { AllowedRequiredModifierType requiredModifiersFound = AllowedRequiredModifierType.None; bool checkRequiredModifiers = true; foreach (CustomModifier modifier in customModifiers) { NamedTypeSymbol modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; if (checkRequiredModifiers && !modifier.IsOptional) { AllowedRequiredModifierType current = AllowedRequiredModifierType.None; if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) != 0 && modifierType.IsWellKnownTypeInAttribute()) { current = AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile) != 0 && modifierType.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit) != 0 && modifierType.IsWellKnownTypeIsExternalInit()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) != 0 && modifierType.IsWellKnownTypeOutAttribute()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute; } if (current == AllowedRequiredModifierType.None || (current != requiredModifiersFound && requiredModifiersFound != AllowedRequiredModifierType.None)) // At the moment we don't support applying different allowed modreqs to the same target. { if (MergeUseSiteInfo(ref result, GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo())) { return true; } checkRequiredModifiers = false; } requiredModifiersFound |= current; } // Unbound generic type is valid as a modifier, let's not report any use site diagnostics because of that. if (modifierType.IsUnboundGenericType) { modifierType = modifierType.OriginalDefinition; } if (DeriveUseSiteInfoFromType(ref result, modifierType)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive<T>(ref DiagnosticInfo result, ImmutableArray<T> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) where T : TypeSymbol { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeWithAnnotations> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<CustomModifier> modifiers, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var modifier in modifiers) { if (((CSharpCustomModifier)modifier).ModifierSymbol.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<ParameterSymbol> parameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, parameter.RefCustomModifiers, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeParameterSymbol> typeParameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var typeParameter in typeParameters) { if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeParameter.ConstraintTypesNoUseSiteDiagnostics, owner, ref checkedTypes)) { return true; } } return false; } #endregion /// <summary> /// True if this symbol has been marked with the <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="ThreeState.Unknown"/> if the <see cref="ObsoleteAttribute"/> attribute hasn't been cracked yet. /// </summary> internal ThreeState ObsoleteState { get { switch (ObsoleteKind) { case ObsoleteAttributeKind.None: case ObsoleteAttributeKind.Experimental: return ThreeState.False; case ObsoleteAttributeKind.Uninitialized: return ThreeState.Unknown; default: return ThreeState.True; } } } internal ObsoleteAttributeKind ObsoleteKind { get { var data = this.ObsoleteAttributeData; return (data == null) ? ObsoleteAttributeKind.None : data.Kind; } } /// <summary> /// Returns data decoded from <see cref="ObsoleteAttribute"/> attribute or null if there is no <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="Microsoft.CodeAnalysis.ObsoleteAttributeData.Uninitialized"/> if attribute arguments haven't been decoded yet. /// </summary> internal abstract ObsoleteAttributeData ObsoleteAttributeData { get; } /// <summary> /// Returns true and a <see cref="string"/> from the first <see cref="GuidAttribute"/> on the symbol, /// the string might be null or an invalid guid representation. False, /// if there is no <see cref="GuidAttribute"/> with string argument. /// </summary> internal bool GetGuidStringDefaultImplementation(out string guidString) { foreach (var attrData in this.GetAttributes()) { if (attrData.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { if (attrData.TryGetGuidAttributeValue(out guidString)) { return true; } } } guidString = null; return false; } public string ToDisplayString(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString(ISymbol, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts(ISymbol, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString(ISymbol, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts(ISymbol, semanticModel, position, format); } internal static void ReportErrorIfHasConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, DiagnosticBag diagnostics) { if (constraintClauses.Count > 0) { diagnostics.Add( ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, constraintClauses[0].WhereKeyword.GetLocation()); } } internal static void CheckForBlockAndExpressionBody( CSharpSyntaxNode block, CSharpSyntaxNode expression, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { if (block != null && expression != null) { diagnostics.Add(ErrorCode.ERR_BlockBodyAndExpressionBody, syntax.GetLocation()); } } [Flags] internal enum ReservedAttributes { DynamicAttribute = 1 << 1, IsReadOnlyAttribute = 1 << 2, IsUnmanagedAttribute = 1 << 3, IsByRefLikeAttribute = 1 << 4, TupleElementNamesAttribute = 1 << 5, NullableAttribute = 1 << 6, NullableContextAttribute = 1 << 7, NullablePublicOnlyAttribute = 1 << 8, NativeIntegerAttribute = 1 << 9, CaseSensitiveExtensionAttribute = 1 << 10, } internal bool ReportExplicitUseOfReservedAttributes(in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, ReservedAttributes reserved) { var attribute = arguments.Attribute; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if ((reserved & ReservedAttributes.DynamicAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute)) { // DynamicAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.IsReadOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsReadOnlyAttribute)) { } else if ((reserved & ReservedAttributes.IsUnmanagedAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsUnmanagedAttribute)) { } else if ((reserved & ReservedAttributes.IsByRefLikeAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsByRefLikeAttribute)) { } else if ((reserved & ReservedAttributes.TupleElementNamesAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute)) { diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableContextAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullableContextAttribute)) { } else if ((reserved & ReservedAttributes.NullablePublicOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullablePublicOnlyAttribute)) { } else if ((reserved & ReservedAttributes.NativeIntegerAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NativeIntegerAttribute)) { } else if ((reserved & ReservedAttributes.CaseSensitiveExtensionAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) { // ExtensionAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location); } else { return false; } return true; bool reportExplicitUseOfReservedAttribute(CSharpAttributeData attribute, in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, in AttributeDescription attributeDescription) { if (attribute.IsTargetAttribute(this, attributeDescription)) { // Do not use '{FullName}'. This is reserved for compiler usage. diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, attributeDescription.FullName); return true; } return false; } } internal virtual byte? GetNullableContextValue() { return GetLocalNullableContextValue() ?? ContainingSymbol?.GetNullableContextValue(); } internal virtual byte? GetLocalNullableContextValue() { return null; } internal void GetCommonNullableValues(CSharpCompilation compilation, ref MostCommonNullableValueBuilder builder) { switch (this.Kind) { case SymbolKind.NamedType: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Event: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((EventSymbol)this).TypeWithAnnotations); } break; case SymbolKind.Field: var field = (FieldSymbol)this; if (field is TupleElementFieldSymbol tupleElement) { field = tupleElement.TupleUnderlyingField; } if (compilation.ShouldEmitNullableAttributes(field)) { builder.AddValue(field.TypeWithAnnotations); } break; case SymbolKind.Method: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Property: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((PropertySymbol)this).TypeWithAnnotations); // Attributes are not emitted for property parameters. } break; case SymbolKind.Parameter: builder.AddValue(((ParameterSymbol)this).TypeWithAnnotations); break; case SymbolKind.TypeParameter: if (this is SourceTypeParameterSymbolBase typeParameter) { builder.AddValue(typeParameter.GetSynthesizedNullableAttributeValue()); foreach (var constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics) { builder.AddValue(constraintType); } } break; } } internal bool ShouldEmitNullableContextValue(out byte value) { byte? localValue = GetLocalNullableContextValue(); if (localValue == null) { value = 0; return false; } value = localValue.GetValueOrDefault(); byte containingValue = ContainingSymbol?.GetNullableContextValue() ?? 0; return value != containingValue; } /// <summary> /// True if the symbol is declared outside of the scope of the containing /// symbol /// </summary> internal static bool IsCaptured(Symbol variable, SourceMethodSymbol containingSymbol) { switch (variable.Kind) { case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: // Range variables are not captured, but their underlying parameters // may be. If this is a range underlying parameter it will be a // ParameterSymbol, not a RangeVariableSymbol. case SymbolKind.RangeVariable: return false; case SymbolKind.Local: if (((LocalSymbol)variable).IsConst) { return false; } break; case SymbolKind.Parameter: break; case SymbolKind.Method: if (variable is LocalFunctionSymbol localFunction) { // calling a static local function doesn't require capturing state if (localFunction.IsStatic) { return false; } break; } throw ExceptionUtilities.UnexpectedValue(variable); default: throw ExceptionUtilities.UnexpectedValue(variable.Kind); } // Walk up the containing symbols until we find the target function, in which // case the variable is not captured by the target function, or null, in which // case it is. for (var currentFunction = variable.ContainingSymbol; (object)currentFunction != null; currentFunction = currentFunction.ContainingSymbol) { if (ReferenceEquals(currentFunction, containingSymbol)) { return false; } } return true; } bool ISymbolInternal.IsStatic { get { return this.IsStatic; } } bool ISymbolInternal.IsVirtual { get { return this.IsVirtual; } } bool ISymbolInternal.IsOverride { get { return this.IsOverride; } } bool ISymbolInternal.IsAbstract { get { return this.IsAbstract; } } Accessibility ISymbolInternal.DeclaredAccessibility { get { return this.DeclaredAccessibility; } } public abstract void Accept(CSharpSymbolVisitor visitor); public abstract TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor); string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } protected abstract ISymbol CreateISymbol(); internal ISymbol ISymbol { get { if (_lazyISymbol is null) { Interlocked.CompareExchange(ref _lazyISymbol, CreateISymbol(), null); } return _lazyISymbol; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion. /// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform /// fashion over the languages. Helpers in this type should only be one of the following forms: /// <list type="bullet"> /// <item> /// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that /// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking' /// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is' /// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the /// raw kind of the node. /// </item> /// <item> /// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs /// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the /// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)' /// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for. /// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use /// 'GetXXXOfYYY' to get that single child. /// </item> /// <item> /// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For /// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and /// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for. /// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate /// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'. /// </item> /// <item> /// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example, /// if certain constructs (like 'patterns') are supported in that language or not. /// </item> /// </list> /// /// <para>Importantly, avoid:</para> /// /// <list type="bullet"> /// <item> /// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName /// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context). /// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right /// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts). /// </item> /// <item> /// Functions which are effectively specific to a single feature are are just trying to find a place to place complex /// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position /// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of /// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in /// its own dedicated service. /// </item> /// <item> /// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or /// some other feature specific service. /// </item> /// <item> /// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'. /// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle /// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs /// to creep in. /// </item> /// <item> /// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression' /// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members. /// </item> /// </list> /// </summary> /// <remarks> /// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either /// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service /// for that purpose if needed by multiple features. /// </remarks> internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfArgument(SyntaxNode node); SyntaxNode GetExpressionOfInterpolation(SyntaxNode node); SyntaxNode GetNameOfAttribute(SyntaxNode node); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); // Violation. Doesn't correspond to any shared structure for vb/c# SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); // Violation. This is a feature level API for QuickInfo. bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); // Violation. This should return a SyntaxList IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); // Violation. This is a feature level API. SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> // Violation. This is a feature level API. bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); // Violation. This is a feature level API. IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); // Violation. This is a feature level API. How 'position' relates to 'containment' is not defined. SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); // Violation. This is a feature level API. [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); // Violation. This is a feature level API. List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); // Violation. This is a feature level API. List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); // Violation. This is a feature level API. bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); // Violation. This is a feature level API. TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> // Violation. This is a feature level API. TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> // Violation. This is a feature level API. SyntaxNode? TryGetBindableParent(SyntaxToken token); // Violation. This is a feature level API. IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); // Violation. This is a feature level API. bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); // Violation. WithXXX methods should not be here, but should be in SyntaxGenerator. [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); // Violation. This is a feature level API. Location GetDeconstructionReferenceLocation(SyntaxNode node); // Violation. This is a feature level API. SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); #region IsXXX members bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); #endregion #region GetPartsOfXXX members void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); #endregion #region GetXXXOfYYYMembers // note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then // ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that // inside ISyntaxFactsExtensions SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); #endregion } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion. /// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform /// fashion over the languages. Helpers in this type should only be one of the following forms: /// <list type="bullet"> /// <item> /// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that /// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking' /// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is' /// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the /// raw kind of the node. /// </item> /// <item> /// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs /// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the /// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)' /// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for. /// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use /// 'GetXXXOfYYY' to get that single child. /// </item> /// <item> /// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For /// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and /// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for. /// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate /// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'. /// </item> /// <item> /// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example, /// if certain constructs (like 'patterns') are supported in that language or not. /// </item> /// </list> /// /// <para>Importantly, avoid:</para> /// /// <list type="bullet"> /// <item> /// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName /// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context). /// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right /// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts). /// </item> /// <item> /// Functions which are effectively specific to a single feature are are just trying to find a place to place complex /// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position /// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of /// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in /// its own dedicated service. /// </item> /// <item> /// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or /// some other feature specific service. /// </item> /// <item> /// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'. /// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle /// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs /// to creep in. /// </item> /// <item> /// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression' /// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members. /// </item> /// </list> /// </summary> /// <remarks> /// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either /// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service /// for that purpose if needed by multiple features. /// </remarks> internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfArgument(SyntaxNode node); SyntaxNode GetExpressionOfInterpolation(SyntaxNode node); SyntaxNode GetNameOfAttribute(SyntaxNode node); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); // Violation. Doesn't correspond to any shared structure for vb/c# SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); // Violation. This is a feature level API for QuickInfo. bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); // Violation. This should return a SyntaxList IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); // Violation. This is a feature level API. SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> // Violation. This is a feature level API. bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); // Violation. This is a feature level API. IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); // Violation. This is a feature level API. How 'position' relates to 'containment' is not defined. SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); // Violation. This is a feature level API. [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); // Violation. This is a feature level API. List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); // Violation. This is a feature level API. List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); // Violation. This is a feature level API. bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); // Violation. This is a feature level API. TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> // Violation. This is a feature level API. TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> // Violation. This is a feature level API. SyntaxNode? TryGetBindableParent(SyntaxToken token); // Violation. This is a feature level API. IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); // Violation. This is a feature level API. bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); // Violation. WithXXX methods should not be here, but should be in SyntaxGenerator. [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); // Violation. This is a feature level API. Location GetDeconstructionReferenceLocation(SyntaxNode node); // Violation. This is a feature level API. SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); #region IsXXX members bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); #endregion #region GetPartsOfXXX members void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); #endregion #region GetXXXOfYYYMembers // note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then // ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that // inside ISyntaxFactsExtensions SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); #endregion } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IVariableDeclaration : SemanticModelTestBase { #region Variable Declarations [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclarator() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'i1' is declared but never used // /*<bind>*/int i1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorWithInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = 1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = 1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/int i1 = 1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorWithInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i1 = ;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // /*<bind>*/int i1 = ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 28) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1, i2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1, i2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'i1' is declared but never used // /*<bind>*/int i1, i2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 23), // CS0168: The variable 'i2' is declared but never used // /*<bind>*/int i1, i2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i2").WithArguments("i2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarationsWithInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = 2, i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = 2, i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 2, i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/int i1 = 2, i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 23), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/int i1 = 2, i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(6, 31) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarationsWithInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = , i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // /*<bind>*/int i1 = , i2 = 2/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 28), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/int i1 = , i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(6, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void InvalidMultipleVariableDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i,;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i,;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i,') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // /*<bind>*/int i,/*</bind>*/; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 25), // CS0168: The variable 'i' is declared but never used // /*<bind>*/int i,/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = GetInt();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleVariableDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i = GetInt(), j = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = Get ... = GetInt();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = Get ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VariableDeclaratorLocalReferenceInitializer() { string source = @" class Program { static void Main(string[] args) { int i = 1; /*<bind>*/int i1 = i;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = i;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MultipleDeclarationsLocalReferenceInitializers() { string source = @" class Program { static void Main(string[] args) { int i = 1; /*<bind>*/int i1 = i, i2 = i1;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = i, i2 = i1;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i, i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidArrayDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int[2, 3] a;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int[2, 3] a;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[2, 3] a') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[2, 3] a;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[2, 3]").WithLocation(6, 22), // file.cs(6,29): warning CS0168: The variable 'a' is declared but never used // /*<bind>*/int[2, 3] a;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidArrayMultipleDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int[2, 3] a, b;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int[2, 3] a, b;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[2, 3] a, b') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32[,] b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[2, 3]").WithLocation(6, 22), // file.cs(6,29): warning CS0168: The variable 'a' is declared but never used // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 29), // file.cs(6,32): warning CS0168: The variable 'b' is declared but never used // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(6, 32) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestGetOperationForVariableInitializer() { string source = @" class Test { void M() { var x /*<bind>*/= 1/*</bind>*/; System.Console.WriteLine(x); } } "; string expectedOperationTree = @" IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_WithInitializer() { string source = @" class C { void M1() { int /*<bind>*/x[10] = 1/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x[10] = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IgnoredArguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(6, 24), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(6, 25), // CS0219: The variable 'x' is assigned but its value is never used // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_NoInitializer() { string source = @" class C { void M1() { int /*<bind>*/x[10]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x[10]') Initializer: null IgnoredArguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(6, 24), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(6, 25), // CS0168: The variable 'x' is declared but never used // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArgumentsWithInitializer_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x[10] = 1/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(2, declarator.Children.Count()); Assert.Equal(OperationKind.Literal, declarator.Children.First().Kind); Assert.Equal(OperationKind.VariableInitializer, declarator.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x[10]/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(1, declarator.Children.Count()); Assert.Equal(OperationKind.Literal, declarator.Children.First().Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_WithInitializer_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x = 1/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(1, declarator.Children.Count()); Assert.Equal(OperationKind.VariableInitializer, declarator.Children.ElementAt(0).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_NoChildren() { string source = @" class C { void M1() { int /*<bind>*/x/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); Assert.Empty(operation.Children); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_WithInitializer() { string source = @" class C { void M1() { /*<bind>*/int[10] x = { 1 };/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10] x = { 1 }') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = { 1 }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= { 1 }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '{ 1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10] x = { 1 };/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(6, 22) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_NoInitializer() { string source = @" class C { void M1() { /*<bind>*/int[10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10] x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(6, 22), // file.cs(6,27): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_InArrayOfArrays() { string source = @" using System; class C { void M1() { /*<bind>*/int[][10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[][10] x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[][] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,24): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[][10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 24), // file.cs(7,29): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[][10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_2ndDimensionOfMultidimensionalArray() { string source = @" using System; class C { void M1() { /*<bind>*/int[,10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[,10] x') Ignored Dimensions(2): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[,10]").WithLocation(7, 22), // file.cs(7,23): error CS0443: Syntax error; value expected // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ValueExpected, "").WithLocation(7, 23), // file.cs(7,28): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 28) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensionsWithInitializer_VerifyChildren() { string source = @" class C { void M1() { /*<bind>*/int[10] x = { 1 }/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclarationSyntax>(compilation); var declaration = (IVariableDeclarationOperation)operation; Assert.Equal(2, declaration.Children.Count()); Assert.Equal(OperationKind.Literal, declaration.Children.First().Kind); Assert.Equal(OperationKind.VariableDeclarator, declaration.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_VerifyChildren() { string source = @" class C { void M1() { /*<bind>*/int[10] x;/*</bind>*/ } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclarationSyntax>(compilation); var declaration = (IVariableDeclarationOperation)operation; Assert.Equal(2, declaration.Children.Count()); Assert.Equal(OperationKind.Literal, declaration.Children.First().Kind); Assert.Equal(OperationKind.VariableDeclarator, declaration.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_VerifyInvalidDimensions() { string source = @" class C { void M1() { int[/*<bind>*/10/*</bind>*/] x; } } "; string expectedOperationTree = "ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10')"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[/*<bind>*/10/*</bind>*/] x; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[/*<bind>*/10/*</bind>*/]").WithLocation(6, 12), // file.cs(6,38): warning CS0168: The variable 'x' is declared but never used // int[/*<bind>*/10/*</bind>*/] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_TestSemanticModel() { string source = @" class C { void M1() { int[10] x; int[M2()] } int M2() => 42; } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var literalExpr = nodes.OfType<LiteralExpressionSyntax>().ElementAt(0); Assert.Equal(@"10", literalExpr.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(literalExpr).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(literalExpr).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(literalExpr)); var invocExpr = nodes.OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal(@"M2()", invocExpr.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(invocExpr).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(invocExpr).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(invocExpr)); var invocInfo = model.GetSymbolInfo(invocExpr); Assert.NotNull(invocInfo.Symbol); Assert.Equal(SymbolKind.Method, invocInfo.Symbol.Kind); Assert.Equal("M2", invocInfo.Symbol.MetadataName); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration() { string source = @" class C { void M1() { /*<bind>*/int[M2(out var z)] x;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(out var z)] x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 22), // file.cs(6,34): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 34), // file.cs(6,38): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InNullableArrayType() { string source = @" class C { void M1() { /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(out var z)]? x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]? x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 22), // file.cs(6,34): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 34), // file.cs(6,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 37), // file.cs(6,39): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 39) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InRefType() { string source = @" class C { void M1() { /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'ref int[M2(out var z)] y') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,26): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 26), // file.cs(6,38): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 38), // file.cs(6,42): error CS8174: A declaration of a by-reference variable must have an initializer // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ByReferenceVariableMustBeInitialized, "y").WithLocation(6, 42), // file.cs(6,42): warning CS0168: The variable 'y' is declared but never used // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InDoublyNestedType() { string source = @" class C { void M1() { /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'ref int[M2( ... var z)]? y') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,26): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 26), // file.cs(6,38): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 38), // file.cs(6,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 41), // file.cs(6,43): error CS8174: A declaration of a by-reference variable must have an initializer // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ByReferenceVariableMustBeInitialized, "y").WithLocation(6, 43), // file.cs(6,43): warning CS0168: The variable 'y' is declared but never used // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_NestedArrayType() { string source = @" class C { #nullable enable void M1() { /*<bind>*/int[10]?[20]? x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10]?[20]? x') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]?[]? x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 22), // file.cs(7,27): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[20]").WithLocation(7, 27), // file.cs(7,33): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 33) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_AliasQualifiedName01() { string source = @" using Col=System.Collections.Generic; class C { void M1() { /*<bind>*/Col::List<int[]> x;/*</bind>*/ } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(10))))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Col::List<int[10]> x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.List<System.Int32[]> x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,32): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/Col::List<int[10]> x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 32), // file.cs(7,38): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/Col::List<int[10]> x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_AliasQualifiedName02() { string source = @" using List=System.Collections.Generic.List<int[10]>; class C { void M1() { /*<bind>*/List x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'List x') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.List<System.Int32[]> x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(2,47): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using List=System.Collections.Generic.List<int[10]>; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(2, 47), // file.cs(8,24): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/List x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(8, 24) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_DeclarationPattern() { string source = @" class C { void M1() { int y = 10; /*<bind>*/int[y is int z] x;/*</bind>*/ z = 34; } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y is int z] x') Ignored Dimensions(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'y is int z') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'y is int z') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y is int z]").WithLocation(7, 22), // file.cs(7,23): error CS0029: Cannot implicitly convert type 'bool' to 'int' // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "y is int z").WithArguments("bool", "int").WithLocation(7, 23), // file.cs(7,35): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 35) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ } int M(int a) => a; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M(y swi ... => 42 })] x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M(System.Int32 a)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(y switch ... z => 42 })') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'y switch { int z => 42 }') ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M(y switch { int z => 42 })]").WithLocation(7, 22), // file.cs(7,52): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 52) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Fixed Statements [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementDeclaration() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p = &reference.i1/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p = &reference.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclaration() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = &reference.i1, p2 = &reference.i2/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p1 = & ... eference.i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = &reference.i2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i2') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i2') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i2') Reference: IFieldReferenceOperation: System.Int32 Program.i2 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i2') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementInvalidAssignment() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p = /*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p = /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p = /*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= /*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // fixed (/*<bind>*/int* p = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 50), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0169: The field 'Program.i1' is never used // int i1; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclarationsInvalidInitializers() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1 = , ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2 = /*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= /*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(10, 40), // CS1525: Invalid expression term ')' // fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 58), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13), // CS0169: The field 'Program.i1' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementNoInitializer() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p").WithLocation(10, 35), // CS0169: The field 'Program.i1' is never used // int i1; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclarationsNoInitializers() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1, p2/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1, p2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(10, 35), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p2").WithLocation(10, 39), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13), // CS0169: The field 'Program.i1' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementInvalidMultipleDeclarations() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1 = & ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') IVariableDeclaratorOperation (Symbol: System.Int32* ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 65), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "").WithLocation(10, 65), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void FixedStatement_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; unsafe { fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) { } } } int M2(int x) => x; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(y sw ... ] p1 = null') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(y switch ... z => 42 })') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'y switch { int z => 42 }') ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= null') ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,9): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(7, 9), // file.cs(9,33): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(y switch { int z => 42 })]").WithLocation(9, 33), // file.cs(9,64): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) Diagnostic(ErrorCode.ERR_BadFixedInitType, "p1 = null").WithLocation(9, 64) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Using Statements [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementDeclaration() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program()/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... w Program()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarations() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program(), p2 = new Program()/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... w Program()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementInvalidInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 =/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // using (/*<bind>*/Program p1 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsInvalidInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2 =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 38), // CS1525: Invalid expression term ')' // using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 55) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementNoInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(8, 34) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsNoInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1, p2/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1, p2') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(8, 34), // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p2").WithLocation(8, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementInvalidMultipleDeclarations() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: Program ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 64), // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "").WithLocation(8, 64) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementExpressionInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = GetProgram()/*</bind>*/) { } } static Program GetProgram() => new Program(); public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... etProgram()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsExpressionInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = GetProgram(), p2 = GetProgram()/*</bind>*/) { } } static Program GetProgram() => new Program(); public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... etProgram()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementLocalReferenceInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { Program p1 = new Program(); using (/*<bind>*/Program p2 = p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p2 = p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsLocalReferenceInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { Program p1 = new Program(); using (/*<bind>*/Program p2 = p1, p3 = p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p2 = p1, p3 = p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') IVariableDeclaratorOperation (Symbol: Program p3) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p3 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingBlock_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using( /*<bind>*/int[] x = new int[0]/*</bind>*/){} } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,25): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/){} Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[y switch { int z => 42 }] x = new int[0]").WithArguments("int[]").WithLocation(7, 25), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/){} Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingStatement_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using( /*<bind>*/int[] x = new int[0]/*</bind>*/); } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,25): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[y switch { int z => 42 }] x = new int[0]").WithArguments("int[]").WithLocation(7, 25), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), // file.cs(7,81): warning CS0642: Possible mistaken empty statement // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(7, 81) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingDeclaration_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,8): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/;").WithArguments("int[]").WithLocation(7, 8), // file.cs(7,27): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region For Loops [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopDeclaration() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = 0/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = 0, j = 0/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0, j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'j' is assigned but its value is never used // for (/*<bind>*/int i = 0, j = 0/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j").WithLocation(6, 35) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // for (/*<bind>*/int i =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsInvalidInitializers() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =, j =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'j =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 31), // CS1525: Invalid expression term ';' // for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 47) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopNoInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'i' // for (/*<bind>*/int i/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsNoInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i, j') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'i' // for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 45), // CS0168: The variable 'j' is declared but never used // for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 31) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopInvalidMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =,/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 31), // CS1001: Identifier expected // for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = GetInt()/*</bind>*/; i < 0; i++) { } } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = GetInt(), j = GetInt()/*</bind>*/; i < 0; i++) { } } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = Get ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void ForLoop_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; for (/*<bind/>*/int[] x = new int[0]/*</bind>*/;;); } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (/*<bind/>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/;;); Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } #endregion #region Const Local Declarations [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = 1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i1 = 1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/const int i1 = 1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarations() { string source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i ... 1, i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1, i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(9, 29), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = ;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // /*<bind>*/const int i1 = ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 34) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsInvalidInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = , i2 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = , i2 = ;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // const /*<bind>*/int i1 = , i2 = /*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 34), // CS1525: Invalid expression term ';' // const /*<bind>*/int i1 = , i2 = /*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationNoInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsNoInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1, i2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1, i2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i2").WithLocation(6, 33), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29), // CS0168: The variable 'i2' is declared but never used // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i2").WithArguments("i2").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalInvalidMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1,;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1,;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1,') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS1001: Identifier expected // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 32), // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, ";").WithLocation(6, 32), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = GetInt();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0133: The expression being assigned to 'i1' must be constant // const /*<bind>*/int i1 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i1").WithLocation(6, 34) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = GetInt(), i2 = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i ... = GetInt();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = Ge ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0133: The expression being assigned to 'i1' must be constant // const /*<bind>*/int i1 = GetInt(), i2 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i1").WithLocation(6, 34), // CS0133: The expression being assigned to 'i2' must be constant // const /*<bind>*/int i1 = GetInt(), i2 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i2").WithLocation(6, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationLocalReferenceInitializer() { string source = @" class Program { static void Main(string[] args) { const int i = 1; /*<bind>*/const int i1 = i;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i1 = i;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // const /*<bind>*/int i1 = i/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsLocalReferenceInitializers() { string source = @" class Program { static void Main(string[] args) { const int i = 1; /*<bind>*/const int i1 = i, i2 = i1;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i ... i, i2 = i1;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i, i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i2' is assigned but its value is never used // const /*<bind>*/int i1 = i, i2 = i1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Control Flow Graph [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_01() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; var b = 2; int c = 3, d = 4; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [System.Int32 c] [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (4) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_02() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a; a = 1; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_03() { string source = @" class C { void M(bool a, int b, int c) /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = a ? b : c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = a ? b : c') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = a ? b : c') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_04() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = ; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // int d = ; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd = ') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd = ') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_05() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used const int d = 1; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 1') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_05_WithControlFlow() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used const int d = true ? 1 : 2; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = true ? 1 : 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = true ? 1 : 2') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_06() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d[10] = 1; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int d[10] = 1; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(7, 14), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int d[10] = 1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(7, 15) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd[10] = 1') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd[10] = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_07() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int = 5; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // int = 5; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 ] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 5') Left: ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 5') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_08() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; ref int b = ref a; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = ref a') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = ref a') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_09() { string source = @" class C { int _c = 1; void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used ref int b = ref _c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = ref _c') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = ref _c') Right: IFieldReferenceOperation: System.Int32 C._c (OperationKind.FieldReference, Type: System.Int32) (Syntax: '_c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '_c') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_10() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used ref int b = 1; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8172: Cannot initialize a by-reference variable with a value // ref int b = 1; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "b = 1").WithLocation(7, 17), // CS1510: A ref or out value must be an assignable variable // ref int b = 1; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(7, 21) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = 1') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_11() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; ref int b = a; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8172: Cannot initialize a by-reference variable with a value // ref int b = a; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "b = a").WithLocation(8, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = a') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = a') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_12() { string source = @" class C { void M(bool a, int b, int c) /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = b, e = a ? b : c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] [System.Int32 e] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = b') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = b') Right: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = a ? b : c') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = a ? b : c') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_13() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used a = 1; int a; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0841: Cannot use local variable 'a' before it is declared // a = 1; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(7, 9) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IVariableDeclaration : SemanticModelTestBase { #region Variable Declarations [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclarator() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'i1' is declared but never used // /*<bind>*/int i1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorWithInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = 1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = 1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/int i1 = 1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorWithInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i1 = ;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // /*<bind>*/int i1 = ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 28) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1, i2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1, i2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'i1' is declared but never used // /*<bind>*/int i1, i2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 23), // CS0168: The variable 'i2' is declared but never used // /*<bind>*/int i1, i2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "i2").WithArguments("i2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarationsWithInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = 2, i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = 2, i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 2, i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/int i1 = 2, i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 23), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/int i1 = 2, i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(6, 31) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleDeclarationsWithInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i1 = , i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // /*<bind>*/int i1 = , i2 = 2/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 28), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/int i1 = , i2 = 2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(6, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void InvalidMultipleVariableDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i,;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int i,;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i,') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // /*<bind>*/int i,/*</bind>*/; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 25), // CS0168: The variable 'i' is declared but never used // /*<bind>*/int i,/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void VariableDeclaratorExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = GetInt();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void MultipleVariableDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int i = GetInt(), j = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = Get ... = GetInt();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = Get ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VariableDeclaratorLocalReferenceInitializer() { string source = @" class Program { static void Main(string[] args) { int i = 1; /*<bind>*/int i1 = i;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = i;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MultipleDeclarationsLocalReferenceInitializers() { string source = @" class Program { static void Main(string[] args) { int i = 1; /*<bind>*/int i1 = i, i2 = i1;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i1 = i, i2 = i1;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i, i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidArrayDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int[2, 3] a;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int[2, 3] a;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[2, 3] a') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[2, 3] a;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[2, 3]").WithLocation(6, 22), // file.cs(6,29): warning CS0168: The variable 'a' is declared but never used // /*<bind>*/int[2, 3] a;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void InvalidArrayMultipleDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/int[2, 3] a, b;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'int[2, 3] a, b;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[2, 3] a, b') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32[,] b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[2, 3]").WithLocation(6, 22), // file.cs(6,29): warning CS0168: The variable 'a' is declared but never used // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 29), // file.cs(6,32): warning CS0168: The variable 'b' is declared but never used // /*<bind>*/int[2, 3] a, b;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(6, 32) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestGetOperationForVariableInitializer() { string source = @" class Test { void M() { var x /*<bind>*/= 1/*</bind>*/; System.Console.WriteLine(x); } } "; string expectedOperationTree = @" IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_WithInitializer() { string source = @" class C { void M1() { int /*<bind>*/x[10] = 1/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x[10] = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IgnoredArguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(6, 24), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(6, 25), // CS0219: The variable 'x' is assigned but its value is never used // int /*<bind>*/x[10] = 1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_NoInitializer() { string source = @" class C { void M1() { int /*<bind>*/x[10]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x[10]') Initializer: null IgnoredArguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(6, 24), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(6, 25), // CS0168: The variable 'x' is declared but never used // int /*<bind>*/x[10]/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 23) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArgumentsWithInitializer_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x[10] = 1/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(2, declarator.Children.Count()); Assert.Equal(OperationKind.Literal, declarator.Children.First().Kind); Assert.Equal(OperationKind.VariableInitializer, declarator.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredArguments_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x[10]/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(1, declarator.Children.Count()); Assert.Equal(OperationKind.Literal, declarator.Children.First().Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_WithInitializer_VerifyChildren() { string source = @" class C { void M1() { int /*<bind>*/x = 1/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); var declarator = (IVariableDeclaratorOperation)operation; Assert.Equal(1, declarator.Children.Count()); Assert.Equal(OperationKind.VariableInitializer, declarator.Children.ElementAt(0).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_NoChildren() { string source = @" class C { void M1() { int /*<bind>*/x/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclaratorSyntax>(compilation); Assert.Empty(operation.Children); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_WithInitializer() { string source = @" class C { void M1() { /*<bind>*/int[10] x = { 1 };/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10] x = { 1 }') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = { 1 }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= { 1 }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '{ 1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }') Element Values(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10] x = { 1 };/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(6, 22) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_NoInitializer() { string source = @" class C { void M1() { /*<bind>*/int[10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10] x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(6, 22), // file.cs(6,27): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_InArrayOfArrays() { string source = @" using System; class C { void M1() { /*<bind>*/int[][10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[][10] x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[][] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,24): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[][10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 24), // file.cs(7,29): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[][10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_2ndDimensionOfMultidimensionalArray() { string source = @" using System; class C { void M1() { /*<bind>*/int[,10] x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[,10] x') Ignored Dimensions(2): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[,] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[,10]").WithLocation(7, 22), // file.cs(7,23): error CS0443: Syntax error; value expected // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ValueExpected, "").WithLocation(7, 23), // file.cs(7,28): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[,10] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 28) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensionsWithInitializer_VerifyChildren() { string source = @" class C { void M1() { /*<bind>*/int[10] x = { 1 }/*</bind>*/; } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclarationSyntax>(compilation); var declaration = (IVariableDeclarationOperation)operation; Assert.Equal(2, declaration.Children.Count()); Assert.Equal(OperationKind.Literal, declaration.Children.First().Kind); Assert.Equal(OperationKind.VariableDeclarator, declaration.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_VerifyChildren() { string source = @" class C { void M1() { /*<bind>*/int[10] x;/*</bind>*/ } } "; var compilation = CreateEmptyCompilation(source); (var operation, _) = GetOperationAndSyntaxForTest<VariableDeclarationSyntax>(compilation); var declaration = (IVariableDeclarationOperation)operation; Assert.Equal(2, declaration.Children.Count()); Assert.Equal(OperationKind.Literal, declaration.Children.First().Kind); Assert.Equal(OperationKind.VariableDeclarator, declaration.Children.ElementAt(1).Kind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_VerifyInvalidDimensions() { string source = @" class C { void M1() { int[/*<bind>*/10/*</bind>*/] x; } } "; string expectedOperationTree = "ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10')"; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[/*<bind>*/10/*</bind>*/] x; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[/*<bind>*/10/*</bind>*/]").WithLocation(6, 12), // file.cs(6,38): warning CS0168: The variable 'x' is declared but never used // int[/*<bind>*/10/*</bind>*/] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_TestSemanticModel() { string source = @" class C { void M1() { int[10] x; int[M2()] } int M2() => 42; } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var literalExpr = nodes.OfType<LiteralExpressionSyntax>().ElementAt(0); Assert.Equal(@"10", literalExpr.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(literalExpr).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(literalExpr).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(literalExpr)); var invocExpr = nodes.OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal(@"M2()", invocExpr.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(invocExpr).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(invocExpr).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(invocExpr)); var invocInfo = model.GetSymbolInfo(invocExpr); Assert.NotNull(invocInfo.Symbol); Assert.Equal(SymbolKind.Method, invocInfo.Symbol.Kind); Assert.Equal("M2", invocInfo.Symbol.MetadataName); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration() { string source = @" class C { void M1() { /*<bind>*/int[M2(out var z)] x;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(out var z)] x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 22), // file.cs(6,34): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 34), // file.cs(6,38): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M2(out var z)] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InNullableArrayType() { string source = @" class C { void M1() { /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(out var z)]? x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]? x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 22), // file.cs(6,34): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 34), // file.cs(6,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 37), // file.cs(6,39): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M2(out var z)]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 39) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InRefType() { string source = @" class C { void M1() { /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'ref int[M2(out var z)] y') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,26): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 26), // file.cs(6,38): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 38), // file.cs(6,42): error CS8174: A declaration of a by-reference variable must have an initializer // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ByReferenceVariableMustBeInitialized, "y").WithLocation(6, 42), // file.cs(6,42): warning CS0168: The variable 'y' is declared but never used // /*<bind>*/ref int[M2(out var z)] y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_OutVarDeclaration_InDoublyNestedType() { string source = @" class C { void M1() { /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ z = 34; } public int M2(out int i) => i = 42; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'ref int[M2( ... var z)]? y') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(out System.Int32 i)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,26): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(out var z)]").WithLocation(6, 26), // file.cs(6,38): warning CS0219: The variable 'z' is assigned but its value is never used // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "z").WithArguments("z").WithLocation(6, 38), // file.cs(6,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 41), // file.cs(6,43): error CS8174: A declaration of a by-reference variable must have an initializer // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.ERR_ByReferenceVariableMustBeInitialized, "y").WithLocation(6, 43), // file.cs(6,43): warning CS0168: The variable 'y' is declared but never used // /*<bind>*/ref int[M2(out var z)]? y;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_NestedArrayType() { string source = @" class C { #nullable enable void M1() { /*<bind>*/int[10]?[20]? x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[10]?[20]? x') Ignored Dimensions(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[]?[]? x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 22), // file.cs(7,27): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[20]").WithLocation(7, 27), // file.cs(7,33): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[10]?[20]? x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 33) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_AliasQualifiedName01() { string source = @" using Col=System.Collections.Generic; class C { void M1() { /*<bind>*/Col::List<int[]> x;/*</bind>*/ } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(10))))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Col::List<int[10]> x') Ignored Dimensions(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.List<System.Int32[]> x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,32): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/Col::List<int[10]> x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(7, 32), // file.cs(7,38): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/Col::List<int[10]> x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_AliasQualifiedName02() { string source = @" using List=System.Collections.Generic.List<int[10]>; class C { void M1() { /*<bind>*/List x;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'List x') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.List<System.Int32[]> x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(2,47): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using List=System.Collections.Generic.List<int[10]>; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[10]").WithLocation(2, 47), // file.cs(8,24): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/List x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(8, 24) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_DeclarationPattern() { string source = @" class C { void M1() { int y = 10; /*<bind>*/int[y is int z] x;/*</bind>*/ z = 34; } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y is int z] x') Ignored Dimensions(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'y is int z') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'y is int z') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y is int z]").WithLocation(7, 22), // file.cs(7,23): error CS0029: Cannot implicitly convert type 'bool' to 'int' // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "y is int z").WithArguments("bool", "int").WithLocation(7, 23), // file.cs(7,35): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[y is int z] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 35) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IVariableDeclaration_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ } int M(int a) => a; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M(y swi ... => 42 })] x') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M(System.Int32 a)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(y switch ... z => 42 })') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'y switch { int z => 42 }') ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,22): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M(y switch { int z => 42 })]").WithLocation(7, 22), // file.cs(7,52): warning CS0168: The variable 'x' is declared but never used // /*<bind>*/int[M(y switch { int z => 42 })] x;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(7, 52) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Fixed Statements [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementDeclaration() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p = &reference.i1/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p = &reference.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclaration() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = &reference.i1, p2 = &reference.i2/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int* p1 = & ... eference.i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = &reference.i2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i2') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i2') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i2') Reference: IFieldReferenceOperation: System.Int32 Program.i2 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i2') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementInvalidAssignment() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p = /*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p = /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p = /*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= /*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // fixed (/*<bind>*/int* p = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 50), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0169: The field 'Program.i1' is never used // int i1; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclarationsInvalidInitializers() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1 = , ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2 = /*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= /*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(10, 40), // CS1525: Invalid expression term ')' // fixed (/*<bind>*/int* p1 = , p2 = /*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 58), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13), // CS0169: The field 'Program.i1' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementNoInitializer() { string source = @" class Program { int i1; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p").WithLocation(10, 35), // CS0169: The field 'Program.i1' is never used // int i1; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementMultipleDeclarationsNoInitializers() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1, p2/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1, p2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32* p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(10, 35), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p2").WithLocation(10, 39), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13), // CS0169: The field 'Program.i1' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i1").WithArguments("Program.i1").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void FixedStatementInvalidMultipleDeclarations() { string source = @" class Program { int i1, i2; static void Main(string[] args) { var reference = new Program(); unsafe { fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) { } } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int* p1 = & ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32* p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = &reference.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= &reference.i1') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '&reference.i1') Children(1): IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&reference.i1') Reference: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'reference.i1') Instance Receiver: ILocalReferenceOperation: reference (OperationKind.LocalReference, Type: Program) (Syntax: 'reference') IVariableDeclaratorOperation (Symbol: System.Int32* ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(10, 65), // CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(8, 9), // CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (/*<bind>*/int* p1 = &reference.i1,/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "").WithLocation(10, 65), // CS0169: The field 'Program.i2' is never used // int i1, i2; Diagnostic(ErrorCode.WRN_UnreferencedField, "i2").WithArguments("Program.i2").WithLocation(4, 13) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void FixedStatement_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; unsafe { fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) { } } } int M2(int x) => x; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[M2(y sw ... ] p1 = null') Ignored Dimensions(1): IInvocationOperation ( System.Int32 C.M2(System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2(y switch ... z => 42 })') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'y switch { int z => 42 }') ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z 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) Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 = null') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= null') ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,9): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(7, 9), // file.cs(9,33): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[M2(y switch { int z => 42 })]").WithLocation(9, 33), // file.cs(9,64): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (/*<bind>*/int[M2(y switch { int z => 42 })] p1 = null/*</bind>*/) Diagnostic(ErrorCode.ERR_BadFixedInitType, "p1 = null").WithLocation(9, 64) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Using Statements [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementDeclaration() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program()/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... w Program()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarations() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program(), p2 = new Program()/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... w Program()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementInvalidInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 =/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ')' // using (/*<bind>*/Program p1 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsInvalidInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1 =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2 =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 38), // CS1525: Invalid expression term ')' // using (/*<bind>*/Program p1 =, p2 =/*</bind>*/) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 55) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementNoInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(8, 34) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsNoInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1, p2/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1, p2') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p1') Initializer: null IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p1").WithLocation(8, 34), // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1, p2/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "p2").WithLocation(8, 38) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementInvalidMultipleDeclarations() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program p1 ... /*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = new Program()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Program()') IObjectCreationOperation (Constructor: Program..ctor()) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program()') Arguments(0) Initializer: null IVariableDeclaratorOperation (Symbol: Program ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 64), // CS0210: You must provide an initializer in a fixed or using statement declaration // using (/*<bind>*/Program p1 = new Program(),/*</bind>*/) Diagnostic(ErrorCode.ERR_FixedMustInit, "").WithLocation(8, 64) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementExpressionInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = GetProgram()/*</bind>*/) { } } static Program GetProgram() => new Program(); public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... etProgram()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsExpressionInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { using (/*<bind>*/Program p1 = GetProgram(), p2 = GetProgram()/*</bind>*/) { } } static Program GetProgram() => new Program(); public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p1 ... etProgram()') Declarators: IVariableDeclaratorOperation (Symbol: Program p1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = GetProgram()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetProgram()') IInvocationOperation (Program Program.GetProgram()) (OperationKind.Invocation, Type: Program) (Syntax: 'GetProgram()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementLocalReferenceInitializer() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { Program p1 = new Program(); using (/*<bind>*/Program p2 = p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p2 = p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void UsingStatementMultipleDeclarationsLocalReferenceInitializers() { string source = @" using System; class Program : IDisposable { static void Main(string[] args) { Program p1 = new Program(); using (/*<bind>*/Program p2 = p1, p3 = p1/*</bind>*/) { } } public void Dispose() { } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Program p2 = p1, p3 = p1') Declarators: IVariableDeclaratorOperation (Symbol: Program p2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p2 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') IVariableDeclaratorOperation (Symbol: Program p3) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p3 = p1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= p1') ILocalReferenceOperation: p1 (OperationKind.LocalReference, Type: Program) (Syntax: 'p1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingBlock_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using( /*<bind>*/int[] x = new int[0]/*</bind>*/){} } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,25): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/){} Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[y switch { int z => 42 }] x = new int[0]").WithArguments("int[]").WithLocation(7, 25), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/){} Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingStatement_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using( /*<bind>*/int[] x = new int[0]/*</bind>*/); } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,25): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[y switch { int z => 42 }] x = new int[0]").WithArguments("int[]").WithLocation(7, 25), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), // file.cs(7,81): warning CS0642: Possible mistaken empty statement // using( /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/); Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(7, 81) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } [Fact] public void UsingDeclaration_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,8): error CS1674: 'int[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/;").WithArguments("int[]").WithLocation(7, 8), // file.cs(7,27): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using /*<bind>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region For Loops [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopDeclaration() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = 0/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = 0, j = 0/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0, j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'j' is assigned but its value is never used // for (/*<bind>*/int i = 0, j = 0/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j").WithLocation(6, 35) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // for (/*<bind>*/int i =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsInvalidInitializers() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =, j =/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'j =/*</bind>*/') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=/*</bind>*/') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 31), // CS1525: Invalid expression term ';' // for (/*<bind>*/int i =, j =/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 47) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopNoInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'i' // for (/*<bind>*/int i/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsNoInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i, j') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'i' // for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 45), // CS0168: The variable 'j' is declared but never used // for (/*<bind>*/int i, j/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 31) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopInvalidMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) { } } } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i =,/*</bind>*/') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i =') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 31), // CS1001: Identifier expected // for (/*<bind>*/int i =,/*</bind>*/; i < 0; i++) Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = GetInt()/*</bind>*/; i < 0; i++) { } } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ForLoopMultipleDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { for (/*<bind>*/int i = GetInt(), j = GetInt()/*</bind>*/; i < 0; i++) { } } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = Get ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void ForLoop_InvalidIgnoredDimensions_SwitchExpression() { string source = @" class C { void M1() { int y = 10; for (/*<bind/>*/int[] x = new int[0]/*</bind>*/;;); } } "; var syntaxTree = Parse(source, filename: "file.cs"); var rankSpecifierOld = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().First(); var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(SyntaxFactory.ParseExpression("y switch { int z => 42 }")))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; string expectedOperationTree = @" IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int[y switc ... new int[0]') Ignored Dimensions(1): ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'y switch { int z => 42 }') Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') Arms(1): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z => 42') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') Locals: Local_1: System.Int32 z Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = new int[0]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new int[0]') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[0]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Initializer: null "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'y' is assigned but its value is never used // int y = 10; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 13), // file.cs(7,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (/*<bind/>*/int[y switch { int z => 42 }] x = new int[0]/*</bind>*/;;); Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[y switch { int z => 42 }]").WithLocation(7, 28), }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclarationSyntax>(new[] { syntaxTree }, expectedOperationTree, expectedDiagnostics); } #endregion #region Const Local Declarations [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclaration() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = 1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i1 = 1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/const int i1 = 1;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarations() { string source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i ... 1, i2 = 2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = 1, i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = 2') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(9, 29), // CS0219: The variable 'i2' is assigned but its value is never used // /*<bind>*/const int i1 = 1, i2 = 2;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationInvalidInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = ;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // /*<bind>*/const int i1 = ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 34) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsInvalidInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = , i2 = ;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = , i2 = ;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = , i2 = ') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2 = ') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ',' // const /*<bind>*/int i1 = , i2 = /*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(6, 34), // CS1525: Invalid expression term ';' // const /*<bind>*/int i1 = , i2 = /*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationNoInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsNoInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1, i2;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1, i2;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i2").WithLocation(6, 33), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29), // CS0168: The variable 'i2' is declared but never used // const /*<bind>*/int i1, i2/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i2").WithArguments("i2").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalInvalidMultipleDeclarations() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1,;/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1,;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1,') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: System.Int32 ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, "i1").WithLocation(6, 29), // CS1001: Identifier expected // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(6, 32), // CS0145: A const field requires a value to be provided // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstValueRequired, ";").WithLocation(6, 32), // CS0168: The variable 'i1' is declared but never used // const /*<bind>*/int i1,/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i1").WithArguments("i1").WithLocation(6, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationExpressionInitializer() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i1 = GetInt();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0133: The expression being assigned to 'i1' must be constant // const /*<bind>*/int i1 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i1").WithLocation(6, 34) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsExpressionInitializers() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/const int i1 = GetInt(), i2 = GetInt();/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const int i ... = GetInt();') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i1 = Ge ... = GetInt()') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2 = GetInt()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= GetInt()') IInvocationOperation (System.Int32 Program.GetInt()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'GetInt()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0133: The expression being assigned to 'i1' must be constant // const /*<bind>*/int i1 = GetInt(), i2 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i1").WithLocation(6, 34), // CS0133: The expression being assigned to 'i2' must be constant // const /*<bind>*/int i1 = GetInt(), i2 = GetInt()/*</bind>*/; Diagnostic(ErrorCode.ERR_NotConstantExpression, "GetInt()").WithArguments("i2").WithLocation(6, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalDeclarationLocalReferenceInitializer() { string source = @" class Program { static void Main(string[] args) { const int i = 1; /*<bind>*/const int i1 = i;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i1 = i;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i1' is assigned but its value is never used // const /*<bind>*/int i1 = i/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")] public void ConstLocalMultipleDeclarationsLocalReferenceInitializers() { string source = @" class Program { static void Main(string[] args) { const int i = 1; /*<bind>*/const int i1 = i, i2 = i1;/*</bind>*/ } static int GetInt() => 1; } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'const int i ... i, i2 = i1;') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i1 = i, i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1 = i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i') IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2 = i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i2' is assigned but its value is never used // const /*<bind>*/int i1 = i, i2 = i1/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } #endregion #region Control Flow Graph [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_01() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; var b = 2; int c = 3, d = 4; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] [System.Int32 c] [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (4) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_02() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a; a = 1; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_03() { string source = @" class C { void M(bool a, int b, int c) /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = a ? b : c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = a ? b : c') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = a ? b : c') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_04() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = ; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ';' // int d = ; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd = ') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd = ') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_05() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used const int d = 1; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 1') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_05_WithControlFlow() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used const int d = true ? 1 : 2; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = true ? 1 : 2') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = true ? 1 : 2') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_06() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d[10] = 1; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int d[10] = 1; Diagnostic(ErrorCode.ERR_CStyleArray, "[10]").WithLocation(7, 14), // CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int d[10] = 1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "10").WithLocation(7, 15) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd[10] = 1') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd[10] = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_07() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int = 5; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1001: Identifier expected // int = 5; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 ] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 5') Left: ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 5') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_08() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; ref int b = ref a; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = ref a') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = ref a') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_09() { string source = @" class C { int _c = 1; void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used ref int b = ref _c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = ref _c') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = ref _c') Right: IFieldReferenceOperation: System.Int32 C._c (OperationKind.FieldReference, Type: System.Int32) (Syntax: '_c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '_c') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_10() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used ref int b = 1; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8172: Cannot initialize a by-reference variable with a value // ref int b = 1; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "b = 1").WithLocation(7, 17), // CS1510: A ref or out value must be an assignable variable // ref int b = 1; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(7, 21) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = 1') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_11() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int a = 1; ref int b = a; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8172: Cannot initialize a by-reference variable with a value // ref int b = a; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "b = a").WithLocation(8, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] [System.Int32 b] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = a') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b = a') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_12() { string source = @" class C { void M(bool a, int b, int c) /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used int d = b, e = a ? b : c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 d] [System.Int32 e] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = b') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd = b') Right: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e = a ? b : c') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e = a ? b : c') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void VariableDeclaration_13() { string source = @" class C { void M() /*<bind>*/{ #pragma warning disable CS0219 // Variable is assigned but its value is never used a = 1; int a; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0841: Cannot use local variable 'a' before it is declared // a = 1; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(7, 9) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } #endregion } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedExplicitImplementationForwardingMethod.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.CSharp.Symbols { /// <summary> /// When C# interface implementation differs from CLR interface implementation, /// we insert a synthesized explicit interface implementation that delegates /// to the method that C# considers an implicit implementation. /// There are two key scenarios for this: /// 1) A single source method is implicitly implementing one or more interface /// methods from metadata and the interface methods have different custom /// modifiers. In this case, we explicitly implement the interface methods /// and have (all) implementations delegate to the source method. /// 2) A non-virtual, non-source method in a base type is implicitly implementing /// an interface method. Since we can't change the "virtualness" of the /// non-source method, we introduce an explicit implementation that delegates /// to it instead. /// </summary> internal sealed partial class SynthesizedExplicitImplementationForwardingMethod : SynthesizedImplementationMethod { private readonly MethodSymbol _implementingMethod; public SynthesizedExplicitImplementationForwardingMethod(MethodSymbol interfaceMethod, MethodSymbol implementingMethod, NamedTypeSymbol implementingType) : base(interfaceMethod, implementingType, generateDebugInfo: false) { _implementingMethod = implementingMethod; } public MethodSymbol ImplementingMethod { get { return _implementingMethod; } } public override MethodKind MethodKind { get { return _implementingMethod.IsAccessor() ? _implementingMethod.MethodKind : MethodKind.ExplicitInterfaceImplementation; } } public override bool IsStatic => _implementingMethod.IsStatic; internal override bool HasSpecialName => false; internal sealed override bool HasRuntimeSpecialName => 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 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// When C# interface implementation differs from CLR interface implementation, /// we insert a synthesized explicit interface implementation that delegates /// to the method that C# considers an implicit implementation. /// There are two key scenarios for this: /// 1) A single source method is implicitly implementing one or more interface /// methods from metadata and the interface methods have different custom /// modifiers. In this case, we explicitly implement the interface methods /// and have (all) implementations delegate to the source method. /// 2) A non-virtual, non-source method in a base type is implicitly implementing /// an interface method. Since we can't change the "virtualness" of the /// non-source method, we introduce an explicit implementation that delegates /// to it instead. /// </summary> internal sealed partial class SynthesizedExplicitImplementationForwardingMethod : SynthesizedImplementationMethod { private readonly MethodSymbol _implementingMethod; public SynthesizedExplicitImplementationForwardingMethod(MethodSymbol interfaceMethod, MethodSymbol implementingMethod, NamedTypeSymbol implementingType) : base(interfaceMethod, implementingType, generateDebugInfo: false) { _implementingMethod = implementingMethod; } public MethodSymbol ImplementingMethod { get { return _implementingMethod; } } public override MethodKind MethodKind { get { return _implementingMethod.IsAccessor() ? _implementingMethod.MethodKind : MethodKind.ExplicitInterfaceImplementation; } } public override bool IsStatic => _implementingMethod.IsStatic; internal override bool HasSpecialName => false; internal sealed override bool HasRuntimeSpecialName => false; } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SingleTC.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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SingleTC : FloatingTC<float>, INumericTC<float> { float INumericTC<float>.MinValue => float.NegativeInfinity; float INumericTC<float>.MaxValue => float.PositiveInfinity; float FloatingTC<float>.NaN => float.NaN; float INumericTC<float>.Zero => 0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public float Next(float value) { Debug.Assert(!float.IsNaN(value)); Debug.Assert(value != float.PositiveInfinity); if (value == 0) return float.Epsilon; if (value < 0) { if (value == -float.Epsilon) return 0.0f; // skip negative zero if (value == float.NegativeInfinity) return float.MinValue; return -UintAsFloat(FloatAsUint(-value) - 1); } if (value == float.MaxValue) return float.PositiveInfinity; return UintAsFloat(FloatAsUint(value) + 1); } private static unsafe uint FloatAsUint(float d) { if (d == 0) return 0; float* dp = &d; uint* lp = (uint*)dp; return *lp; } private static unsafe float UintAsFloat(uint l) { uint* lp = &l; float* dp = (float*)lp; return *dp; } bool INumericTC<float>.Related(BinaryOperatorKind relation, float left, float right) { switch (relation) { case Equal: return left == right || float.IsNaN(left) && float.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } float INumericTC<float>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0F : constantValue.SingleValue; ConstantValue INumericTC<float>.ToConstantValue(float value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<float>.ToString(float value) => float.IsNaN(value) ? "NaN" : value == float.NegativeInfinity ? "-Inf" : value == float.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G9}"); float INumericTC<float>.Prev(float value) { return -Next(-value); } float INumericTC<float>.Random(Random random) { return (float)(random.NextDouble() * 100 - 50); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SingleTC : FloatingTC<float>, INumericTC<float> { float INumericTC<float>.MinValue => float.NegativeInfinity; float INumericTC<float>.MaxValue => float.PositiveInfinity; float FloatingTC<float>.NaN => float.NaN; float INumericTC<float>.Zero => 0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public float Next(float value) { Debug.Assert(!float.IsNaN(value)); Debug.Assert(value != float.PositiveInfinity); if (value == 0) return float.Epsilon; if (value < 0) { if (value == -float.Epsilon) return 0.0f; // skip negative zero if (value == float.NegativeInfinity) return float.MinValue; return -UintAsFloat(FloatAsUint(-value) - 1); } if (value == float.MaxValue) return float.PositiveInfinity; return UintAsFloat(FloatAsUint(value) + 1); } private static unsafe uint FloatAsUint(float d) { if (d == 0) return 0; float* dp = &d; uint* lp = (uint*)dp; return *lp; } private static unsafe float UintAsFloat(uint l) { uint* lp = &l; float* dp = (float*)lp; return *dp; } bool INumericTC<float>.Related(BinaryOperatorKind relation, float left, float right) { switch (relation) { case Equal: return left == right || float.IsNaN(left) && float.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } float INumericTC<float>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0F : constantValue.SingleValue; ConstantValue INumericTC<float>.ToConstantValue(float value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<float>.ToString(float value) => float.IsNaN(value) ? "NaN" : value == float.NegativeInfinity ? "-Inf" : value == float.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G9}"); float INumericTC<float>.Prev(float value) { return -Next(-value); } float INumericTC<float>.Random(Random random) { return (float)(random.NextDouble() * 100 - 50); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/LanguageServer/Protocol/ILspLoggerFactory.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.LanguageServer; using StreamJsonRpc; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal interface ILspLoggerFactory { Task<ILspLogger> CreateLoggerAsync(string serverTypeName, string? clientName, JsonRpc jsonRpc, 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.LanguageServer; using StreamJsonRpc; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal interface ILspLoggerFactory { Task<ILspLogger> CreateLoggerAsync(string serverTypeName, string? clientName, JsonRpc jsonRpc, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/StaticKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StaticKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validNonInterfaceMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validInterfaceMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.SealedKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.UnsafeKeyword }; public StaticKeywordRecommender() : base(SyntaxKind.StaticKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.TargetToken.IsUsingKeywordInUsingDirective() || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken) || context.SyntaxTree.IsLambdaDeclarationContext(position, otherModifier: SyntaxKind.AsyncKeyword, cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validNonInterfaceMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validInterfaceMemberModifiers, validTypeDeclarations: SyntaxKindSet.InterfaceOnlyTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsTypeDeclarationContext( validModifiers: s_validTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StaticKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validNonInterfaceMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validInterfaceMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.SealedKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.UnsafeKeyword }; public StaticKeywordRecommender() : base(SyntaxKind.StaticKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.TargetToken.IsUsingKeywordInUsingDirective() || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken) || context.SyntaxTree.IsLambdaDeclarationContext(position, otherModifier: SyntaxKind.AsyncKeyword, cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validNonInterfaceMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validInterfaceMemberModifiers, validTypeDeclarations: SyntaxKindSet.InterfaceOnlyTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsTypeDeclarationContext( validModifiers: s_validTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/UnaryExpression.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { // These tests handle changing between different unary expressions public class UnaryExpression { [Fact] public void PlusToNegate() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression); } [Fact] public void PlusToAddressOf() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.AddressOfExpression); } [Fact] public void PlusToBitwiseNot() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.BitwiseNotExpression); } [Fact] public void PlusToLogicalNot() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.LogicalNotExpression); } [Fact] public void PlusToPointerIndirect() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression); } [Fact] public void PlusToPreDecrement() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PreDecrementExpression); } [Fact] public void PlusToPreIncrement() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PreIncrementExpression); } #region Helpers private static void MakeUnaryChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeUnaryChanges(oldStyle, newStyle); MakeUnaryChanges(oldStyle, newStyle, options: TestOptions.Script); MakeUnaryChanges(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeUnaryChanges(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = oldName + " y"; // Be warned when changing the fields here var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var treeNode = topLevel ? GetGlobalExpressionNode(newTree) : GetExpressionNode(newTree); Assert.Equal(treeNode.Kind(), newSyntaxKind); } private static PrefixUnaryExpressionSyntax GetExpressionNode(SyntaxTree newTree) { var classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; var expression = statement.Expression as PrefixUnaryExpressionSyntax; return expression; } private static PrefixUnaryExpressionSyntax GetGlobalExpressionNode(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; var expression = statement.Expression as PrefixUnaryExpressionSyntax; return expression; } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.UnaryPlusExpression: return "+"; case SyntaxKind.UnaryMinusExpression: return "-"; case SyntaxKind.BitwiseNotExpression: return "~"; case SyntaxKind.LogicalNotExpression: return "!"; case SyntaxKind.PreIncrementExpression: return "++"; case SyntaxKind.PreDecrementExpression: return "--"; case SyntaxKind.PointerIndirectionExpression: return "*"; case SyntaxKind.AddressOfExpression: return "&"; default: throw new Exception("Unexpected case"); } } #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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { // These tests handle changing between different unary expressions public class UnaryExpression { [Fact] public void PlusToNegate() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression); } [Fact] public void PlusToAddressOf() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.AddressOfExpression); } [Fact] public void PlusToBitwiseNot() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.BitwiseNotExpression); } [Fact] public void PlusToLogicalNot() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.LogicalNotExpression); } [Fact] public void PlusToPointerIndirect() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression); } [Fact] public void PlusToPreDecrement() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PreDecrementExpression); } [Fact] public void PlusToPreIncrement() { MakeUnaryChange(SyntaxKind.UnaryPlusExpression, SyntaxKind.PreIncrementExpression); } #region Helpers private static void MakeUnaryChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeUnaryChanges(oldStyle, newStyle); MakeUnaryChanges(oldStyle, newStyle, options: TestOptions.Script); MakeUnaryChanges(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeUnaryChanges(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = oldName + " y"; // Be warned when changing the fields here var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var treeNode = topLevel ? GetGlobalExpressionNode(newTree) : GetExpressionNode(newTree); Assert.Equal(treeNode.Kind(), newSyntaxKind); } private static PrefixUnaryExpressionSyntax GetExpressionNode(SyntaxTree newTree) { var classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; var expression = statement.Expression as PrefixUnaryExpressionSyntax; return expression; } private static PrefixUnaryExpressionSyntax GetGlobalExpressionNode(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; var expression = statement.Expression as PrefixUnaryExpressionSyntax; return expression; } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.UnaryPlusExpression: return "+"; case SyntaxKind.UnaryMinusExpression: return "-"; case SyntaxKind.BitwiseNotExpression: return "~"; case SyntaxKind.LogicalNotExpression: return "!"; case SyntaxKind.PreIncrementExpression: return "++"; case SyntaxKind.PreDecrementExpression: return "--"; case SyntaxKind.PointerIndirectionExpression: return "*"; case SyntaxKind.AddressOfExpression: return "&"; default: throw new Exception("Unexpected case"); } } #endregion } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.GenerationVerifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Test.Utilities; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal partial class EditAndContinueTest { internal sealed class GenerationVerifier { private readonly int _ordinal; private readonly MetadataReader _metadataReader; private readonly IEnumerable<MetadataReader> _readers; public GenerationVerifier(int ordinal, MetadataReader metadataReader, IEnumerable<MetadataReader> readers) { _ordinal = ordinal; _metadataReader = metadataReader; _readers = readers; } private string GetAssertMessage(string message) { var ordinalDescription = _ordinal == 0 ? "initial baseline" : $"generation {_ordinal}"; return $"Failure in {ordinalDescription}: {message}"; } internal void VerifyTypeDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetTypeDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("TypeDefs don't match")); } internal void VerifyMethodDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMethodDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MethodDefs don't match")); } internal void VerifyMemberRefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMemberRefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MemberRefs don't match")); } internal void VerifyFieldDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetFieldDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("FieldDefs don't match")); } internal void VerifyPropertyDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetPropertyDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("PropertyDefs don't match")); } internal void VerifyTableSize(TableIndex table, int expected) { AssertEx.AreEqual(expected, _metadataReader.GetTableRowCount(table), message: GetAssertMessage($"{table} table size doesnt't match")); } internal void VerifyEncLog(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog doesn't match")); } internal void VerifyEncMap(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap doesn't match")); } internal void VerifyEncLogDefinitions(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog definitions don't match")); } internal void VerifyEncMapDefinitions(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap definitions don't match")); } internal void VerifyCustomAttributes(IEnumerable<CustomAttributeRow> expected) { AssertEx.Equal(expected, _metadataReader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Test.Utilities; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal partial class EditAndContinueTest { internal sealed class GenerationVerifier { private readonly int _ordinal; private readonly MetadataReader _metadataReader; private readonly IEnumerable<MetadataReader> _readers; public GenerationVerifier(int ordinal, MetadataReader metadataReader, IEnumerable<MetadataReader> readers) { _ordinal = ordinal; _metadataReader = metadataReader; _readers = readers; } private string GetAssertMessage(string message) { var ordinalDescription = _ordinal == 0 ? "initial baseline" : $"generation {_ordinal}"; return $"Failure in {ordinalDescription}: {message}"; } internal void VerifyTypeDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetTypeDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("TypeDefs don't match")); } internal void VerifyMethodDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMethodDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MethodDefs don't match")); } internal void VerifyMemberRefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMemberRefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MemberRefs don't match")); } internal void VerifyFieldDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetFieldDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("FieldDefs don't match")); } internal void VerifyPropertyDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetPropertyDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("PropertyDefs don't match")); } internal void VerifyTableSize(TableIndex table, int expected) { AssertEx.AreEqual(expected, _metadataReader.GetTableRowCount(table), message: GetAssertMessage($"{table} table size doesnt't match")); } internal void VerifyEncLog(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog doesn't match")); } internal void VerifyEncMap(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap doesn't match")); } internal void VerifyEncLogDefinitions(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog definitions don't match")); } internal void VerifyEncMapDefinitions(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap definitions don't match")); } internal void VerifyCustomAttributes(IEnumerable<CustomAttributeRow> expected) { AssertEx.Equal(expected, _metadataReader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/Core/Def/Implementation/VisualStudioSupportsFeatureService.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SuggestionService { internal sealed class VisualStudioSupportsFeatureService { private const string ContainedLanguageMarker = nameof(ContainedLanguageMarker); [ExportWorkspaceService(typeof(ITextBufferSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioTextBufferSupportsFeatureService : ITextBufferSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextBufferSupportsFeatureService() { } public bool SupportsCodeFixes(ITextBuffer textBuffer) { return SupportsCodeFixesWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRefactorings(ITextBuffer textBuffer) { return SupportsRefactoringsWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRename(ITextBuffer textBuffer) { // TS creates generated documents to back script blocks in razor generated files. // These files are opened in the roslyn workspace but are not valid to rename // as they are not proper buffers. So we exclude any buffer that is marked as a contained language. if (textBuffer.Properties.TryGetProperty<bool>(ContainedLanguageMarker, out var markerValue) && markerValue) { return false; } var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { var documentId = workspace.GetDocumentIdInCurrentContext(sourceTextContainer); return SupportsRenameWorker(workspace.CurrentSolution.GetRelatedDocumentIds(documentId)); } return false; } public bool SupportsNavigationToAnyPosition(ITextBuffer textBuffer) => SupportsNavigationToAnyPositionWorker(GetContainedDocumentId(textBuffer)); private static DocumentId GetContainedDocumentId(ITextBuffer textBuffer) { var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace) && workspace is VisualStudioWorkspaceImpl vsWorkspace) { return vsWorkspace.GetDocumentIdInCurrentContext(sourceTextContainer); } return null; } } [ExportWorkspaceService(typeof(IDocumentSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioDocumentSupportsFeatureService : IDocumentSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentSupportsFeatureService() { } public bool SupportsCodeFixes(Document document) => SupportsCodeFixesWorker(document.Id); public bool SupportsRefactorings(Document document) => SupportsRefactoringsWorker(document.Id); public bool SupportsRename(Document document) => SupportsRenameWorker(document.Project.Solution.GetRelatedDocumentIds(document.Id)); public bool SupportsNavigationToAnyPosition(Document document) => SupportsNavigationToAnyPositionWorker(document.Id); } private static bool SupportsCodeFixesWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRefactoringsWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRenameWorker(ImmutableArray<DocumentId> ids) { return ids.Select(id => ContainedDocument.TryGetContainedDocument(id)) .All(cd => cd == null || cd.SupportsRename); } private static bool SupportsNavigationToAnyPositionWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SuggestionService { internal sealed class VisualStudioSupportsFeatureService { private const string ContainedLanguageMarker = nameof(ContainedLanguageMarker); [ExportWorkspaceService(typeof(ITextBufferSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioTextBufferSupportsFeatureService : ITextBufferSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextBufferSupportsFeatureService() { } public bool SupportsCodeFixes(ITextBuffer textBuffer) { return SupportsCodeFixesWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRefactorings(ITextBuffer textBuffer) { return SupportsRefactoringsWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRename(ITextBuffer textBuffer) { // TS creates generated documents to back script blocks in razor generated files. // These files are opened in the roslyn workspace but are not valid to rename // as they are not proper buffers. So we exclude any buffer that is marked as a contained language. if (textBuffer.Properties.TryGetProperty<bool>(ContainedLanguageMarker, out var markerValue) && markerValue) { return false; } var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { var documentId = workspace.GetDocumentIdInCurrentContext(sourceTextContainer); return SupportsRenameWorker(workspace.CurrentSolution.GetRelatedDocumentIds(documentId)); } return false; } public bool SupportsNavigationToAnyPosition(ITextBuffer textBuffer) => SupportsNavigationToAnyPositionWorker(GetContainedDocumentId(textBuffer)); private static DocumentId GetContainedDocumentId(ITextBuffer textBuffer) { var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace) && workspace is VisualStudioWorkspaceImpl vsWorkspace) { return vsWorkspace.GetDocumentIdInCurrentContext(sourceTextContainer); } return null; } } [ExportWorkspaceService(typeof(IDocumentSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioDocumentSupportsFeatureService : IDocumentSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentSupportsFeatureService() { } public bool SupportsCodeFixes(Document document) => SupportsCodeFixesWorker(document.Id); public bool SupportsRefactorings(Document document) => SupportsRefactoringsWorker(document.Id); public bool SupportsRename(Document document) => SupportsRenameWorker(document.Project.Solution.GetRelatedDocumentIds(document.Id)); public bool SupportsNavigationToAnyPosition(Document document) => SupportsNavigationToAnyPositionWorker(document.Id); } private static bool SupportsCodeFixesWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRefactoringsWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRenameWorker(ImmutableArray<DocumentId> ids) { return ids.Select(id => ContainedDocument.TryGetContainedDocument(id)) .All(cd => cd == null || cd.SupportsRename); } private static bool SupportsNavigationToAnyPositionWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() { [||]Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() => [||]Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() { [||]Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() => [||]Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicIntelliSense.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicIntelliSense : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicIntelliSense(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicIntelliSense)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); // Disable import completion. VisualStudio.Workspace.SetImportCompletionOption(false); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.Completion)] public void IntelliSenseTriggersOnParenWithBraceCompletionAndCorrectUndoMerging() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim q as lis("); VisualStudio.Editor.Verify.CompletionItemsExist("Of"); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send( VirtualKey.Down, VirtualKey.Tab); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(" inte"); VisualStudio.Editor.Verify.CompletionItemsExist("Integer"); VisualStudio.SendKeys.Send(')'); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of Integer)$$ End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of inte)$$ End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of inte$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As lis($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As lis($$ End Sub End Module", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/45234"), Trait(Traits.Feature, Traits.Features.Completion)] public void TypeAVariableDeclaration() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim"); VisualStudio.Editor.Verify.CompletionItemsExist("Dim", "ReDim"); VisualStudio.SendKeys.Send(' '); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send('i'); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.CompletionItemsExist("As"); VisualStudio.SendKeys.Send("a "); VisualStudio.SendKeys.Send("intege"); VisualStudio.Editor.Verify.CompletionItemsExist("Integer", "UInteger"); VisualStudio.SendKeys.Send(' '); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send('='); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send("fooo"); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(VirtualKey.Backspace); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(VirtualKey.Backspace); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send( VirtualKey.Left, VirtualKey.Delete); Assert.True(VisualStudio.Editor.IsCompletionActive()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void DismissIntelliSenseOnApostrophe() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim q as "); VisualStudio.Editor.Verify.CompletionItemsExist("_AppDomain"); VisualStudio.SendKeys.Send("'"); Assert.False(VisualStudio.Editor.IsCompletionActive()); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Module Module1 Sub Main() Dim q As ' End Sub End Module", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeLeftAngleAfterImports() { SetUpEditor(@" Imports$$"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.CompletionItemsExist("Microsoft", "System"); VisualStudio.SendKeys.Send('<'); Assert.False(VisualStudio.Editor.IsCompletionActive()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void DismissAndRetriggerIntelliSenseOnEquals() { SetUpEditor(@" Module Module1 Function M(val As Integer) As Integer $$ End Function End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send('M'); VisualStudio.Editor.Verify.CompletionItemsExist("M"); VisualStudio.SendKeys.Send("=v"); VisualStudio.Editor.Verify.CompletionItemsExist("val"); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Function M(val As Integer) As Integer M=val $$ End Function End Module", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void CtrlAltSpace() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Namespace Foo$$", assertCaretPosition: true); ClearEditor(); VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Space, ShiftState.Ctrl | ShiftState.Alt)); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Nam Foo$$", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void CtrlAltSpaceOption() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Namespace Foo$$", assertCaretPosition: true); ClearEditor(); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_ToggleCompletionMode); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Nam Foo$$", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void EnterTriggerCompletionListAndImplementInterface() { SetUpEditor(@" Interface UFoo Sub FooBar() End Interface Public Class Bar Implements$$ End Class"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send(" UF"); VisualStudio.Editor.Verify.CompletionItemsExist("UFoo"); VisualStudio.SendKeys.Send(VirtualKey.Enter); Assert.False(VisualStudio.Editor.IsCompletionActive()); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" Interface UFoo Sub FooBar() End Interface Public Class Bar Implements UFoo Public Sub FooBar() Implements UFoo.FooBar Throw New NotImplementedException() End Sub End Class", actualText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicIntelliSense : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicIntelliSense(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicIntelliSense)) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); // Disable import completion. VisualStudio.Workspace.SetImportCompletionOption(false); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.Completion)] public void IntelliSenseTriggersOnParenWithBraceCompletionAndCorrectUndoMerging() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim q as lis("); VisualStudio.Editor.Verify.CompletionItemsExist("Of"); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send( VirtualKey.Down, VirtualKey.Tab); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(" inte"); VisualStudio.Editor.Verify.CompletionItemsExist("Integer"); VisualStudio.SendKeys.Send(')'); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of Integer)$$ End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of inte)$$ End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of inte$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List(Of$$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As List($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As lis($$) End Sub End Module", assertCaretPosition: true); VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z)); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Sub Main() Dim q As lis($$ End Sub End Module", assertCaretPosition: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/45234"), Trait(Traits.Feature, Traits.Features.Completion)] public void TypeAVariableDeclaration() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim"); VisualStudio.Editor.Verify.CompletionItemsExist("Dim", "ReDim"); VisualStudio.SendKeys.Send(' '); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send('i'); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.CompletionItemsExist("As"); VisualStudio.SendKeys.Send("a "); VisualStudio.SendKeys.Send("intege"); VisualStudio.Editor.Verify.CompletionItemsExist("Integer", "UInteger"); VisualStudio.SendKeys.Send(' '); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send('='); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send("fooo"); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(' '); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(VirtualKey.Backspace); Assert.False(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send(VirtualKey.Backspace); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.SendKeys.Send( VirtualKey.Left, VirtualKey.Delete); Assert.True(VisualStudio.Editor.IsCompletionActive()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void DismissIntelliSenseOnApostrophe() { SetUpEditor(@" Module Module1 Sub Main() $$ End Sub End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("dim q as "); VisualStudio.Editor.Verify.CompletionItemsExist("_AppDomain"); VisualStudio.SendKeys.Send("'"); Assert.False(VisualStudio.Editor.IsCompletionActive()); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Module Module1 Sub Main() Dim q As ' End Sub End Module", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeLeftAngleAfterImports() { SetUpEditor(@" Imports$$"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.CompletionItemsExist("Microsoft", "System"); VisualStudio.SendKeys.Send('<'); Assert.False(VisualStudio.Editor.IsCompletionActive()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void DismissAndRetriggerIntelliSenseOnEquals() { SetUpEditor(@" Module Module1 Function M(val As Integer) As Integer $$ End Function End Module"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send('M'); VisualStudio.Editor.Verify.CompletionItemsExist("M"); VisualStudio.SendKeys.Send("=v"); VisualStudio.Editor.Verify.CompletionItemsExist("val"); VisualStudio.SendKeys.Send(' '); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Function M(val As Integer) As Integer M=val $$ End Function End Module", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void CtrlAltSpace() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Namespace Foo$$", assertCaretPosition: true); ClearEditor(); VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Space, ShiftState.Ctrl | ShiftState.Alt)); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Nam Foo$$", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void CtrlAltSpaceOption() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Namespace Foo$$", assertCaretPosition: true); ClearEditor(); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_ToggleCompletionMode); VisualStudio.SendKeys.Send("Nam Foo"); VisualStudio.Editor.Verify.CurrentLineText("Nam Foo$$", assertCaretPosition: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void EnterTriggerCompletionListAndImplementInterface() { SetUpEditor(@" Interface UFoo Sub FooBar() End Interface Public Class Bar Implements$$ End Class"); VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.SendKeys.Send(" UF"); VisualStudio.Editor.Verify.CompletionItemsExist("UFoo"); VisualStudio.SendKeys.Send(VirtualKey.Enter); Assert.False(VisualStudio.Editor.IsCompletionActive()); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" Interface UFoo Sub FooBar() End Interface Public Class Bar Implements UFoo Public Sub FooBar() Implements UFoo.FooBar Throw New NotImplementedException() End Sub End Class", actualText); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/CSharp/Portable/Completion/CompletionProviders/SpeculativeTCompletionProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SpeculativeTCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(AwaitCompletionProvider))] [Shared] internal class SpeculativeTCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SpeculativeTCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var showSpeculativeT = await document.IsValidContextForDocumentOrLinkedDocumentsAsync( (doc, ct) => ShouldShowSpeculativeTCompletionItemAsync(doc, position, ct), cancellationToken).ConfigureAwait(false); if (showSpeculativeT) { const string T = nameof(T); context.AddItem(CommonCompletionItem.Create( T, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.TypeParameter)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static async Task<bool> ShouldShowSpeculativeTCompletionItemAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) { return false; } // We could be in the middle of a ref/generic/tuple type, instead of a simple T case. // If we managed to walk out and get a different SpanStart, we treat it as a simple $$T case. var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.Parent, cancellationToken).ConfigureAwait(false); var spanStart = position; while (true) { var oldSpanStart = spanStart; spanStart = WalkOutOfGenericType(syntaxTree, spanStart, semanticModel, cancellationToken); spanStart = WalkOutOfTupleType(syntaxTree, spanStart, cancellationToken); spanStart = WalkOutOfRefType(syntaxTree, spanStart, cancellationToken); if (spanStart == oldSpanStart) { break; } } return IsStartOfSpeculativeTContext(syntaxTree, spanStart, cancellationToken); } private static bool IsStartOfSpeculativeTContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsMemberDeclarationContext(position, contextOpt: null, SyntaxKindSet.AllMemberModifiers, SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken) || syntaxTree.IsStatementContext(position, token, cancellationToken) || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || syntaxTree.IsGlobalStatementContext(position, cancellationToken) || syntaxTree.IsDelegateReturnTypeContext(position, token); } private static int WalkOutOfGenericType(SyntaxTree syntaxTree, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { var spanStart = position; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (syntaxTree.IsGenericTypeArgumentContext(position, token, cancellationToken, semanticModel)) { if (syntaxTree.IsInPartiallyWrittenGeneric(spanStart, cancellationToken, out var nameToken)) { spanStart = nameToken.SpanStart; } // If the user types Goo<T, automatic brace completion will insert the close brace // and the generic won't be "partially written". if (spanStart == position) { spanStart = token.GetAncestor<GenericNameSyntax>()?.SpanStart ?? spanStart; } var tokenLeftOfGenericName = syntaxTree.FindTokenOnLeftOfPosition(spanStart, cancellationToken); if (tokenLeftOfGenericName.IsKind(SyntaxKind.DotToken) && tokenLeftOfGenericName.Parent.IsKind(SyntaxKind.QualifiedName)) { spanStart = tokenLeftOfGenericName.Parent.SpanStart; } } return spanStart; } private static int WalkOutOfRefType(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var prevToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (prevToken.IsKind(SyntaxKind.RefKeyword, SyntaxKind.ReadOnlyKeyword) && prevToken.Parent.IsKind(SyntaxKind.RefType)) { return prevToken.SpanStart; } return position; } private static int WalkOutOfTupleType(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var prevToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (prevToken.IsPossibleTupleOpenParenOrComma()) { return prevToken.Parent.SpanStart; } return position; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SpeculativeTCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(AwaitCompletionProvider))] [Shared] internal class SpeculativeTCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SpeculativeTCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var showSpeculativeT = await document.IsValidContextForDocumentOrLinkedDocumentsAsync( (doc, ct) => ShouldShowSpeculativeTCompletionItemAsync(doc, position, ct), cancellationToken).ConfigureAwait(false); if (showSpeculativeT) { const string T = nameof(T); context.AddItem(CommonCompletionItem.Create( T, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.TypeParameter)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static async Task<bool> ShouldShowSpeculativeTCompletionItemAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) { return false; } // We could be in the middle of a ref/generic/tuple type, instead of a simple T case. // If we managed to walk out and get a different SpanStart, we treat it as a simple $$T case. var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.Parent, cancellationToken).ConfigureAwait(false); var spanStart = position; while (true) { var oldSpanStart = spanStart; spanStart = WalkOutOfGenericType(syntaxTree, spanStart, semanticModel, cancellationToken); spanStart = WalkOutOfTupleType(syntaxTree, spanStart, cancellationToken); spanStart = WalkOutOfRefType(syntaxTree, spanStart, cancellationToken); if (spanStart == oldSpanStart) { break; } } return IsStartOfSpeculativeTContext(syntaxTree, spanStart, cancellationToken); } private static bool IsStartOfSpeculativeTContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsMemberDeclarationContext(position, contextOpt: null, SyntaxKindSet.AllMemberModifiers, SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken) || syntaxTree.IsStatementContext(position, token, cancellationToken) || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || syntaxTree.IsGlobalStatementContext(position, cancellationToken) || syntaxTree.IsDelegateReturnTypeContext(position, token); } private static int WalkOutOfGenericType(SyntaxTree syntaxTree, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { var spanStart = position; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (syntaxTree.IsGenericTypeArgumentContext(position, token, cancellationToken, semanticModel)) { if (syntaxTree.IsInPartiallyWrittenGeneric(spanStart, cancellationToken, out var nameToken)) { spanStart = nameToken.SpanStart; } // If the user types Goo<T, automatic brace completion will insert the close brace // and the generic won't be "partially written". if (spanStart == position) { spanStart = token.GetAncestor<GenericNameSyntax>()?.SpanStart ?? spanStart; } var tokenLeftOfGenericName = syntaxTree.FindTokenOnLeftOfPosition(spanStart, cancellationToken); if (tokenLeftOfGenericName.IsKind(SyntaxKind.DotToken) && tokenLeftOfGenericName.Parent.IsKind(SyntaxKind.QualifiedName)) { spanStart = tokenLeftOfGenericName.Parent.SpanStart; } } return spanStart; } private static int WalkOutOfRefType(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var prevToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (prevToken.IsKind(SyntaxKind.RefKeyword, SyntaxKind.ReadOnlyKeyword) && prevToken.Parent.IsKind(SyntaxKind.RefType)) { return prevToken.SpanStart; } return position; } private static int WalkOutOfTupleType(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var prevToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (prevToken.IsPossibleTupleOpenParenOrComma()) { return prevToken.Parent.SpanStart; } return position; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/CoreTest/CodeCleanup/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { using Microsoft.CodeAnalysis; using CSharp = Microsoft.CodeAnalysis.CSharp; public static class Extensions { public static TextSpan GetCodeCleanupSpan(this SyntaxNode node) { var previousToken = node.GetFirstToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true).GetPreviousToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); var endToken = node.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true).GetNextToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); return TextSpan.FromBounds(previousToken.SpanStart, endToken.Span.End); } public static T GetMember<T>(this Document document, int index) where T : SyntaxNode => (T)document.GetSyntaxRootAsync().Result.GetMember(index); public static T GetMember<T>(this T node, int index) where T : SyntaxNode { dynamic d = node; return (T)d.Members[index]; } public static T RemoveCSharpMember<T>(this T node, int index) where T : SyntaxNode { var newMembers = CSharp.SyntaxFactory.List(node.RemoveMember<CSharp.Syntax.MemberDeclarationSyntax>(index)); dynamic d = node; return (T)d.WithMembers(newMembers); } public static T AddCSharpMember<T>(this T node, CSharp.Syntax.MemberDeclarationSyntax member, int index) where T : SyntaxNode { var newMembers = CSharp.SyntaxFactory.List(node.AddMember<CSharp.Syntax.MemberDeclarationSyntax>(member, index)); dynamic d = node; return (T)d.WithMembers(newMembers); } public static IEnumerable<M> RemoveMember<M>(this SyntaxNode node, int index) where M : SyntaxNode { dynamic d = node; var members = ((IEnumerable<M>)d.Members).ToList(); members.RemoveAt(index); return members; } public static IEnumerable<M> AddMember<M>(this SyntaxNode node, M member, int index) where M : SyntaxNode { dynamic d = node; var members = ((IEnumerable<M>)d.Members).ToList(); members.Insert(index, member); return members; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { using Microsoft.CodeAnalysis; using CSharp = Microsoft.CodeAnalysis.CSharp; public static class Extensions { public static TextSpan GetCodeCleanupSpan(this SyntaxNode node) { var previousToken = node.GetFirstToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true).GetPreviousToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); var endToken = node.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true).GetNextToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true); return TextSpan.FromBounds(previousToken.SpanStart, endToken.Span.End); } public static T GetMember<T>(this Document document, int index) where T : SyntaxNode => (T)document.GetSyntaxRootAsync().Result.GetMember(index); public static T GetMember<T>(this T node, int index) where T : SyntaxNode { dynamic d = node; return (T)d.Members[index]; } public static T RemoveCSharpMember<T>(this T node, int index) where T : SyntaxNode { var newMembers = CSharp.SyntaxFactory.List(node.RemoveMember<CSharp.Syntax.MemberDeclarationSyntax>(index)); dynamic d = node; return (T)d.WithMembers(newMembers); } public static T AddCSharpMember<T>(this T node, CSharp.Syntax.MemberDeclarationSyntax member, int index) where T : SyntaxNode { var newMembers = CSharp.SyntaxFactory.List(node.AddMember<CSharp.Syntax.MemberDeclarationSyntax>(member, index)); dynamic d = node; return (T)d.WithMembers(newMembers); } public static IEnumerable<M> RemoveMember<M>(this SyntaxNode node, int index) where M : SyntaxNode { dynamic d = node; var members = ((IEnumerable<M>)d.Members).ToList(); members.RemoveAt(index); return members; } public static IEnumerable<M> AddMember<M>(this SyntaxNode node, M member, int index) where M : SyntaxNode { dynamic d = node; var members = ((IEnumerable<M>)d.Members).ToList(); members.Insert(index, member); return members; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharpTest/Diagnostics/ConvertToAsync/ConvertToAsyncTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ConvertToAsync { using VerifyCS = CSharpCodeFixVerifier< EmptyDiagnosticAnalyzer, CSharpConvertToAsyncMethodCodeFixProvider>; public class ConvertToAsyncTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToAsync)] public async Task CantAwaitAsyncVoid() { var initial = @"using System.Threading.Tasks; class Program { async Task rtrt() { {|CS4008:await gt()|}; } async void gt() { } }"; var expected = @"using System.Threading.Tasks; class Program { async Task rtrt() { await gt(); } async Task gt() { } }"; await VerifyCS.VerifyCodeFixAsync(initial, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ConvertToAsync { using VerifyCS = CSharpCodeFixVerifier< EmptyDiagnosticAnalyzer, CSharpConvertToAsyncMethodCodeFixProvider>; public class ConvertToAsyncTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToAsync)] public async Task CantAwaitAsyncVoid() { var initial = @"using System.Threading.Tasks; class Program { async Task rtrt() { {|CS4008:await gt()|}; } async void gt() { } }"; var expected = @"using System.Threading.Tasks; class Program { async Task rtrt() { await gt(); } async Task gt() { } }"; await VerifyCS.VerifyCodeFixAsync(initial, expected); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.DefinitionTrackingContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitionsAsync"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitionsAsync"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/FormatLargeBinaryExpressionRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal partial class AbstractGenerateEqualsAndGetHashCodeService { /// <summary> /// Specialized formatter for the "return a == obj.a &amp;&amp; b == obj.b &amp;&amp; c == obj.c &amp;&amp; ... /// code that we spit out. /// </summary> private class FormatLargeBinaryExpressionRule : AbstractFormattingRule { private readonly ISyntaxFactsService _syntaxFacts; public FormatLargeBinaryExpressionRule(ISyntaxFactsService syntaxFacts) => _syntaxFacts = syntaxFacts; /// <summary> /// Wrap the large &amp;&amp; expression after every &amp;&amp; token. /// </summary> public override AdjustNewLinesOperation? GetAdjustNewLinesOperation( in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (_syntaxFacts.IsLogicalAndExpression(previousToken.Parent)) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } return nextOperation.Invoke(in previousToken, in currentToken); } /// <summary> /// Align all the wrapped parts of the expression with the token after 'return'. /// That way we get: /// /// return a == obj.a &amp;&amp; /// b == obj.b &amp;&amp; /// ... /// </summary> public override void AddIndentBlockOperations( List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { if (_syntaxFacts.IsReturnStatement(node)) { var expr = _syntaxFacts.GetExpressionOfReturnStatement(node); if (expr?.ChildNodesAndTokens().Count > 1) { list.Add(FormattingOperations.CreateRelativeIndentBlockOperation( expr.GetFirstToken(), expr.GetFirstToken().GetNextToken(), node.GetLastToken(), indentationDelta: 0, option: IndentBlockOption.RelativePosition)); return; } } nextOperation.Invoke(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal partial class AbstractGenerateEqualsAndGetHashCodeService { /// <summary> /// Specialized formatter for the "return a == obj.a &amp;&amp; b == obj.b &amp;&amp; c == obj.c &amp;&amp; ... /// code that we spit out. /// </summary> private class FormatLargeBinaryExpressionRule : AbstractFormattingRule { private readonly ISyntaxFactsService _syntaxFacts; public FormatLargeBinaryExpressionRule(ISyntaxFactsService syntaxFacts) => _syntaxFacts = syntaxFacts; /// <summary> /// Wrap the large &amp;&amp; expression after every &amp;&amp; token. /// </summary> public override AdjustNewLinesOperation? GetAdjustNewLinesOperation( in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (_syntaxFacts.IsLogicalAndExpression(previousToken.Parent)) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } return nextOperation.Invoke(in previousToken, in currentToken); } /// <summary> /// Align all the wrapped parts of the expression with the token after 'return'. /// That way we get: /// /// return a == obj.a &amp;&amp; /// b == obj.b &amp;&amp; /// ... /// </summary> public override void AddIndentBlockOperations( List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { if (_syntaxFacts.IsReturnStatement(node)) { var expr = _syntaxFacts.GetExpressionOfReturnStatement(node); if (expr?.ChildNodesAndTokens().Count > 1) { list.Add(FormattingOperations.CreateRelativeIndentBlockOperation( expr.GetFirstToken(), expr.GetFirstToken().GetNextToken(), node.GetLastToken(), indentationDelta: 0, option: IndentBlockOption.RelativePosition)); return; } } nextOperation.Invoke(); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/NamespaceDeclarationPreference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CodeStyle { internal enum NamespaceDeclarationPreference { /// <summary> /// Prefer <c>namespace N { }</c> /// </summary> BlockScoped, /// <summary> /// Prefer <c>namespace N;</c> /// </summary> FileScoped, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CodeStyle { internal enum NamespaceDeclarationPreference { /// <summary> /// Prefer <c>namespace N { }</c> /// </summary> BlockScoped, /// <summary> /// Prefer <c>namespace N;</c> /// </summary> FileScoped, } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Semantic/Semantics/UsingDeclarationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { /// <summary> /// Tests related to binding (but not lowering) using declarations (i.e. using var x = ...). /// </summary> public class UsingDeclarationTests : CompilingTestBase { [Fact] public void UsingVariableIsNotReportedAsUnused() { var source = @" using System; class C { static void Main() { using var x = (IDisposable)null; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void DisallowGoToForwardAcrossUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9) ); } [Fact] public void DisallowGoToForwardAcrossUsingDeclarationsFromLowerBlock() { var source = @" using System; class C { static void Main() { { goto label1; } using var x = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(8, 13), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(10, 9) ); } [Fact] public void DisallowGoToForwardAcrossMultipleUsingDeclarationsGivesOnlyOneDiagnostic() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; using var y = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9) ); } [Fact] public void DisallowMultipleGoToForwardAcrossMultipleUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; goto label2; using var y = (IDisposable)null; label1: label2: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9), // (9,9): error CS8641: A goto target can not be after any using declarations. // goto label2; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label2;").WithLocation(9, 9) ); } [Fact] public void DisallowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInTheSameScope() { var source = @" using System; class C { static void Main() { label1: using var x = (IDisposable)null; goto label1; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(10, 9) ); } [Fact] public void DisallowGoToBackwardsAcrossUsingDeclarationsWithMultipleLabels() { var source = @" using System; class C { static void Main() { label1: label2: label3: using var x = (IDisposable)null; goto label3; // disallowed } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(7, 9), // (8,9): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2").WithLocation(8, 9), // (10,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label3; // disallowed Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(12, 9) ); } [Fact] public void DisallowGoToAcrossUsingDeclarationsComplexTest() { var source = @" using System; #pragma warning disable 162 // disable unreachable code warnings class C { static void Main() { label1: { label2: using var a = (IDisposable)null; goto label1; // allowed goto label2; // disallowed 1 } label3: using var b = (IDisposable)null; { goto label3; // disallowed 2 } { goto label4; // allowed goto label5; // disallowed 3 label4: using var c = (IDisposable)null; label5: using var d = (IDisposable)null; } using var e = (IDisposable)null; label6: { { goto label6; //allowed label7: { label8: using var f = (IDisposable)null; goto label7; // allowed { using var g = (IDisposable)null; goto label7; //allowed goto label8; // disallowed 4 } } } } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label2; // disallowed 1 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label2;").WithLocation(14, 13), // (20,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label3; // disallowed 2 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(20, 13), // (25,13): error CS8641: A goto cannot jump to a location after a using declaration. // goto label5; // disallowed 3 Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label5;").WithLocation(25, 13), // (45,25): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label8; // disallowed 4 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label8;").WithLocation(45, 25) ); } [Fact] public void AllowGoToAroundUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; label1: using var x = (IDisposable)null; goto label2; label2: return; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInHigherScope() { var source = @" using System; class C { static void Main() { label1: { using var x = (IDisposable)null; goto label1; } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowGoToForwardsAcrossUsingDeclarationsInALowerBlock() { var source = @" using System; class C { static void Main() { goto label1; { using var x = (IDisposable)null; } label1: ; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(9, 13) ); } [Fact] public void AllowGoToBackwardsAcrossUsingDeclarationsInALowerBlock() { var source = @" using System; class C { static void Main() { label1: { using var x = (IDisposable)null; } goto label1; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableCanBeInitializedWithExistingDisposable() { var source = @" using System; class C2 : IDisposable { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { var x = new C2(); using var x2 = x; using var x3 = x2; x = null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCanBeInitializedWithExistingDisposableInASingleStatement() { var source = @" using System; class C2 : IDisposable { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { using C2 x = new C2(), x2 = x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCanBeInitializedWithExistingRefStructDisposable() { var source = @" using System; ref struct C2 { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { var x = new C2(); using var x2 = x; using var x3 = x2; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCannotBeReAssigned() { var source = @" using System; class C { static void Main() { using var x = (IDisposable)null; x = null; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS1656: Cannot assign to 'x' because it is a 'using variable' // x = null; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(8, 9) ); } [Fact] public void UsingVariableCannotBeUsedAsOutVariable() { var source = @" using System; class C { static void Consume(out IDisposable x) { x = null; } static void Main() { using var x = (IDisposable)null; Consume(out x); } } "; CreateCompilation(source).VerifyDiagnostics( // (13,21): error CS1657: Cannot use 'x' as a ref or out value because it is a 'using variable' // Consume(out x); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(13, 21) ); } [Fact] public void UsingVariableMustHaveInitializer() { var source = @" using System; class C { static void Main() { using IDisposable x; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using IDisposable x; Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(7, 27) ); } [Fact] public void UsingVariableFromExistingVariable() { var source = @" using System; class C { static void Main() { var x = (IDisposable)null; using var x2 = x; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableFromExpression() { var source = @" using System; class C { static IDisposable GetDisposable() { return null; } static void Main() { using IDisposable x = GetDisposable(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableFromAwaitExpression() { var source = @" using System; using System.Threading.Tasks; class C { static Task<IDisposable> GetDisposable() { return Task.FromResult<IDisposable>(null); } static async Task Main() { using IDisposable x = await GetDisposable(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableInSwitchCase() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void Main() { int x = 5; switch (x) { case 5: using C1 o1 = new C1(); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,21): error CS8389: 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(15, 17) ); } [Fact] public void UsingVariableDiagnosticsInDeclarationAreOnlyEmittedOnce() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void Main() { using var c1 = new C1(), c2 = new C2(); } }"; CreateCompilation(source).VerifyDiagnostics( // (11,15): error CS0819: Implicitly-typed variables cannot have multiple declarators // using var c1 = new C1(), c2 = new C2(); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C1(), c2 = new C2()").WithLocation(11, 15) ); } [Fact] public void UsingDeclarationWithAwaitsInAsync() { var source = @" using System; using System.Threading.Tasks; class C2 : IDisposable { public string ID { get; set; } public void Dispose() { Console.Write($""Dispose {ID}; ""); } } class C { static async Task<IDisposable> GetDisposable(string id) { await Task.Yield(); return new C2(){ ID = id }; } static async Task Main() { using IDisposable x = await GetDisposable(""c1""); await Task.Yield(); Console.Write(""after c1; ""); using IDisposable y = await GetDisposable(""c2""); Console.Write(""after c2; ""); } } "; var compilation = CreateCompilationWithTasksExtensions(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "after c1; after c2; Dispose c2; Dispose c1; "); } [Fact] public void UsingDeclarationsWithLangVer7_3() { var source = @" using System; class C { static void Main() { using IDisposable x = null; } } "; var expected = new[] { // (7,9): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // using IDisposable x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(7, 9) }; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void AwaitUsingDeclarationsWithLangVer7_3() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await using IAsyncDisposable x = null; } } "; var expected = new[] { // (8,15): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // await using IAsyncDisposable x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(8, 15) }; CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected); CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void UsingDeclarationsWithObsoleteTypes() { var source = @" using System; [Obsolete] class C1 : IDisposable { [Obsolete] public void Dispose() { } } class C2 : IDisposable { [Obsolete] public void Dispose() { } } ref struct S3 { [Obsolete] public void Dispose() { } } class C4 { static void Main() { // c1 is obsolete using C1 c1 = new C1(); // no warning, we don't warn on dispose being obsolete because it comes through interface using C2 c2 = new C2(); // warning, we're calling the pattern based obsolete method for the ref struct using S3 S3 = new S3(); } } "; CreateCompilation(source).VerifyDiagnostics( // (34,15): warning CS0612: 'C1' is obsolete // using C1 c1 = new C1(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 15), // (34,27): warning CS0612: 'C1' is obsolete // using C1 c1 = new C1(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 27), // (40,15): warning CS0612: 'S3.Dispose()' is obsolete // using S3 S3 = new S3(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "using S3 S3 = new S3();").WithArguments("S3.Dispose()").WithLocation(40, 9) ); } [Fact] [WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")] public void UsingDeclarationsWithInvalidModifiers() { var source = @" using System; class C { static void Main() { using public readonly var x = (IDisposable)null; } } "; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,15): error CS0106: The modifier 'public' is not valid for this item // using public readonly var x = (IDisposable)null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(7, 15), // (7,22): error CS0106: The modifier 'readonly' is not valid for this item // using public readonly var x = (IDisposable)null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(7, 22) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { /// <summary> /// Tests related to binding (but not lowering) using declarations (i.e. using var x = ...). /// </summary> public class UsingDeclarationTests : CompilingTestBase { [Fact] public void UsingVariableIsNotReportedAsUnused() { var source = @" using System; class C { static void Main() { using var x = (IDisposable)null; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void DisallowGoToForwardAcrossUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9) ); } [Fact] public void DisallowGoToForwardAcrossUsingDeclarationsFromLowerBlock() { var source = @" using System; class C { static void Main() { { goto label1; } using var x = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(8, 13), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(10, 9) ); } [Fact] public void DisallowGoToForwardAcrossMultipleUsingDeclarationsGivesOnlyOneDiagnostic() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; using var y = (IDisposable)null; label1: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9) ); } [Fact] public void DisallowMultipleGoToForwardAcrossMultipleUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; using var x = (IDisposable)null; goto label2; using var y = (IDisposable)null; label1: label2: return; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9), // (9,9): error CS8641: A goto target can not be after any using declarations. // goto label2; Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label2;").WithLocation(9, 9) ); } [Fact] public void DisallowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInTheSameScope() { var source = @" using System; class C { static void Main() { label1: using var x = (IDisposable)null; goto label1; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label1; Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(10, 9) ); } [Fact] public void DisallowGoToBackwardsAcrossUsingDeclarationsWithMultipleLabels() { var source = @" using System; class C { static void Main() { label1: label2: label3: using var x = (IDisposable)null; goto label3; // disallowed } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(7, 9), // (8,9): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2").WithLocation(8, 9), // (10,9): error CS8641: A goto target within the same block can not cross a using declaration. // goto label3; // disallowed Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(12, 9) ); } [Fact] public void DisallowGoToAcrossUsingDeclarationsComplexTest() { var source = @" using System; #pragma warning disable 162 // disable unreachable code warnings class C { static void Main() { label1: { label2: using var a = (IDisposable)null; goto label1; // allowed goto label2; // disallowed 1 } label3: using var b = (IDisposable)null; { goto label3; // disallowed 2 } { goto label4; // allowed goto label5; // disallowed 3 label4: using var c = (IDisposable)null; label5: using var d = (IDisposable)null; } using var e = (IDisposable)null; label6: { { goto label6; //allowed label7: { label8: using var f = (IDisposable)null; goto label7; // allowed { using var g = (IDisposable)null; goto label7; //allowed goto label8; // disallowed 4 } } } } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label2; // disallowed 1 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label2;").WithLocation(14, 13), // (20,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label3; // disallowed 2 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(20, 13), // (25,13): error CS8641: A goto cannot jump to a location after a using declaration. // goto label5; // disallowed 3 Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label5;").WithLocation(25, 13), // (45,25): error CS8642: A goto cannot jump to a location before a using declaration within the same block. // goto label8; // disallowed 4 Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label8;").WithLocation(45, 25) ); } [Fact] public void AllowGoToAroundUsingDeclarations() { var source = @" using System; class C { static void Main() { goto label1; label1: using var x = (IDisposable)null; goto label2; label2: return; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInHigherScope() { var source = @" using System; class C { static void Main() { label1: { using var x = (IDisposable)null; goto label1; } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowGoToForwardsAcrossUsingDeclarationsInALowerBlock() { var source = @" using System; class C { static void Main() { goto label1; { using var x = (IDisposable)null; } label1: ; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,9): warning CS0162: Unreachable code detected // using var x = (IDisposable)null; Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(9, 13) ); } [Fact] public void AllowGoToBackwardsAcrossUsingDeclarationsInALowerBlock() { var source = @" using System; class C { static void Main() { label1: { using var x = (IDisposable)null; } goto label1; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableCanBeInitializedWithExistingDisposable() { var source = @" using System; class C2 : IDisposable { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { var x = new C2(); using var x2 = x; using var x3 = x2; x = null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCanBeInitializedWithExistingDisposableInASingleStatement() { var source = @" using System; class C2 : IDisposable { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { using C2 x = new C2(), x2 = x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCanBeInitializedWithExistingRefStructDisposable() { var source = @" using System; ref struct C2 { public void Dispose() { Console.Write(""Disposed; ""); } } class C { static void Main() { var x = new C2(); using var x2 = x; using var x3 = x2; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; "); } [Fact] public void UsingVariableCannotBeReAssigned() { var source = @" using System; class C { static void Main() { using var x = (IDisposable)null; x = null; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS1656: Cannot assign to 'x' because it is a 'using variable' // x = null; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(8, 9) ); } [Fact] public void UsingVariableCannotBeUsedAsOutVariable() { var source = @" using System; class C { static void Consume(out IDisposable x) { x = null; } static void Main() { using var x = (IDisposable)null; Consume(out x); } } "; CreateCompilation(source).VerifyDiagnostics( // (13,21): error CS1657: Cannot use 'x' as a ref or out value because it is a 'using variable' // Consume(out x); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(13, 21) ); } [Fact] public void UsingVariableMustHaveInitializer() { var source = @" using System; class C { static void Main() { using IDisposable x; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using IDisposable x; Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(7, 27) ); } [Fact] public void UsingVariableFromExistingVariable() { var source = @" using System; class C { static void Main() { var x = (IDisposable)null; using var x2 = x; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableFromExpression() { var source = @" using System; class C { static IDisposable GetDisposable() { return null; } static void Main() { using IDisposable x = GetDisposable(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableFromAwaitExpression() { var source = @" using System; using System.Threading.Tasks; class C { static Task<IDisposable> GetDisposable() { return Task.FromResult<IDisposable>(null); } static async Task Main() { using IDisposable x = await GetDisposable(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingVariableInSwitchCase() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void Main() { int x = 5; switch (x) { case 5: using C1 o1 = new C1(); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,21): error CS8389: 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(15, 17) ); } [Fact] public void UsingVariableDiagnosticsInDeclarationAreOnlyEmittedOnce() { var source = @" using System; class C1 : IDisposable { public void Dispose() { } } class C2 { public static void Main() { using var c1 = new C1(), c2 = new C2(); } }"; CreateCompilation(source).VerifyDiagnostics( // (11,15): error CS0819: Implicitly-typed variables cannot have multiple declarators // using var c1 = new C1(), c2 = new C2(); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C1(), c2 = new C2()").WithLocation(11, 15) ); } [Fact] public void UsingDeclarationWithAwaitsInAsync() { var source = @" using System; using System.Threading.Tasks; class C2 : IDisposable { public string ID { get; set; } public void Dispose() { Console.Write($""Dispose {ID}; ""); } } class C { static async Task<IDisposable> GetDisposable(string id) { await Task.Yield(); return new C2(){ ID = id }; } static async Task Main() { using IDisposable x = await GetDisposable(""c1""); await Task.Yield(); Console.Write(""after c1; ""); using IDisposable y = await GetDisposable(""c2""); Console.Write(""after c2; ""); } } "; var compilation = CreateCompilationWithTasksExtensions(source, options: TestOptions.DebugExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "after c1; after c2; Dispose c2; Dispose c1; "); } [Fact] public void UsingDeclarationsWithLangVer7_3() { var source = @" using System; class C { static void Main() { using IDisposable x = null; } } "; var expected = new[] { // (7,9): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // using IDisposable x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(7, 9) }; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void AwaitUsingDeclarationsWithLangVer7_3() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await using IAsyncDisposable x = null; } } "; var expected = new[] { // (8,15): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // await using IAsyncDisposable x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(8, 15) }; CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected); CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void UsingDeclarationsWithObsoleteTypes() { var source = @" using System; [Obsolete] class C1 : IDisposable { [Obsolete] public void Dispose() { } } class C2 : IDisposable { [Obsolete] public void Dispose() { } } ref struct S3 { [Obsolete] public void Dispose() { } } class C4 { static void Main() { // c1 is obsolete using C1 c1 = new C1(); // no warning, we don't warn on dispose being obsolete because it comes through interface using C2 c2 = new C2(); // warning, we're calling the pattern based obsolete method for the ref struct using S3 S3 = new S3(); } } "; CreateCompilation(source).VerifyDiagnostics( // (34,15): warning CS0612: 'C1' is obsolete // using C1 c1 = new C1(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 15), // (34,27): warning CS0612: 'C1' is obsolete // using C1 c1 = new C1(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 27), // (40,15): warning CS0612: 'S3.Dispose()' is obsolete // using S3 S3 = new S3(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "using S3 S3 = new S3();").WithArguments("S3.Dispose()").WithLocation(40, 9) ); } [Fact] [WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")] public void UsingDeclarationsWithInvalidModifiers() { var source = @" using System; class C { static void Main() { using public readonly var x = (IDisposable)null; } } "; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,15): error CS0106: The modifier 'public' is not valid for this item // using public readonly var x = (IDisposable)null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(7, 15), // (7,22): error CS0106: The modifier 'readonly' is not valid for this item // using public readonly var x = (IDisposable)null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(7, 22) ); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/StackAllocKeywordRecommender.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.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more 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.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Helper class for "Fix all occurrences" code fix providers. /// </summary> internal sealed class BatchFixAllProvider : FixAllProvider { public static readonly FixAllProvider Instance = new BatchFixAllProvider(); private BatchFixAllProvider() { } public override Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext) => DefaultFixAllProviderHelpers.GetFixAsync( FixAllContextHelper.GetDefaultFixAllTitle(fixAllContext), fixAllContext, FixAllContextsAsync); private async Task<Solution?> FixAllContextsAsync( FixAllContext originalFixAllContext, ImmutableArray<FixAllContext> fixAllContexts) { var cancellationToken = originalFixAllContext.CancellationToken; var progressTracker = originalFixAllContext.GetProgressTracker(); progressTracker.Description = FixAllContextHelper.GetDefaultFixAllTitle(originalFixAllContext); // We have 2*P + 1 pieces of work. Computing diagnostics and fixes/changes per context, and then one pass // applying fixes. progressTracker.AddItems(fixAllContexts.Length * 2 + 1); // Mapping from document to the cumulative text changes created for that document. var docIdToTextMerger = new Dictionary<DocumentId, TextChangeMerger>(); // Process each context one at a time, allowing us to dump most of the information we computed for each once // done with it. The only information we need to preserve is the data we store in docIdToTextMerger foreach (var fixAllContext in fixAllContexts) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project); await FixSingleContextAsync(fixAllContext, progressTracker, docIdToTextMerger).ConfigureAwait(false); } // Finally, merge in all text changes into the solution. We can't do this per-project as we have to have // process *all* diagnostics in the solution to find the changes made to all documents. using (progressTracker.ItemCompletedScope()) { if (docIdToTextMerger.Count == 0) return null; var currentSolution = originalFixAllContext.Solution; foreach (var group in docIdToTextMerger.GroupBy(kvp => kvp.Key.ProjectId)) currentSolution = await ApplyChangesAsync(currentSolution, group.SelectAsArray(kvp => (kvp.Key, kvp.Value)), cancellationToken).ConfigureAwait(false); return currentSolution; } } private static async Task FixSingleContextAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { // First, determine the diagnostics to fix for that context. var documentToDiagnostics = await DetermineDiagnosticsAsync(fixAllContext, progressTracker).ConfigureAwait(false); // Second, process all those diagnostics, merging the cumulative set of text changes per document into docIdToTextMerger. await AddDocumentChangesAsync(fixAllContext, progressTracker, docIdToTextMerger, documentToDiagnostics).ConfigureAwait(false); } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> DetermineDiagnosticsAsync(FixAllContext fixAllContext, IProgressTracker progressTracker) { using var _ = progressTracker.ItemCompletedScope(); var documentToDiagnostics = await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(false); var filtered = documentToDiagnostics.Where(kvp => { if (kvp.Key.Project != fixAllContext.Project) return false; if (fixAllContext.Document != null && fixAllContext.Document != kvp.Key) return false; return true; }); return filtered.ToImmutableDictionary(); } private static async Task AddDocumentChangesAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger, ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentToDiagnostics) { using var _ = progressTracker.ItemCompletedScope(); // First, order the diagnostics so we process them in a consistent manner and get the same results given the // same input solution. var orderedDiagnostics = documentToDiagnostics.SelectMany(kvp => kvp.Value) .Where(d => d.Location.IsInSource) .OrderBy(d => d.Location.SourceTree!.FilePath) .ThenBy(d => d.Location.SourceSpan.Start) .ToImmutableArray(); // Now determine all the document changes caused from these diagnostics. var allChangedDocumentsInDiagnosticsOrder = await GetAllChangedDocumentsInDiagnosticsOrderAsync(fixAllContext, orderedDiagnostics).ConfigureAwait(false); // Finally, take all the changes made to each document and merge them together into docIdToTextMerger to // keep track of the total set of changes to any particular document. await MergeTextChangesAsync(fixAllContext, allChangedDocumentsInDiagnosticsOrder, docIdToTextMerger).ConfigureAwait(false); } /// <summary> /// Returns all the changed documents produced by fixing the list of provided <paramref /// name="orderedDiagnostics"/>. The documents will be returned such that fixed documents for a later /// diagnostic will appear later than those for an earlier diagnostic. /// </summary> private static async Task<ImmutableArray<Document>> GetAllChangedDocumentsInDiagnosticsOrderAsync( FixAllContext fixAllContext, ImmutableArray<Diagnostic> orderedDiagnostics) { var solution = fixAllContext.Solution; var cancellationToken = fixAllContext.CancellationToken; // Process each diagnostic, determine the code actions to fix it, then figure out the document changes // produced by that code action. using var _1 = ArrayBuilder<Task<ImmutableArray<Document>>>.GetInstance(out var tasks); foreach (var diagnostic in orderedDiagnostics) { var document = solution.GetRequiredDocument(diagnostic.Location.SourceTree!); cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(async () => { // Create a context that will add the reported code actions into this using var _2 = ArrayBuilder<CodeAction>.GetInstance(out var codeActions); var context = new CodeFixContext(document, diagnostic, GetRegisterCodeFixAction(fixAllContext.CodeActionEquivalenceKey, codeActions), cancellationToken); // Wait for the all the code actions to be reported for this diagnostic. var registerTask = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; await registerTask.ConfigureAwait(false); // Now, process each code action and find out all the document changes caused by it. using var _3 = ArrayBuilder<Document>.GetInstance(out var changedDocuments); foreach (var codeAction in codeActions) { var changedSolution = await codeAction.GetChangedSolutionInternalAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (changedSolution != null) { var changedDocumentIds = new SolutionChanges(changedSolution, solution).GetProjectChanges().SelectMany(p => p.GetChangedDocuments()); changedDocuments.AddRange(changedDocumentIds.Select(id => changedSolution.GetRequiredDocument(id))); } } return changedDocuments.ToImmutable(); }, cancellationToken)); } // Wait for all that work to finish. await Task.WhenAll(tasks).ConfigureAwait(false); // Flatten the set of changed documents. These will naturally still be ordered by the diagnostic that // caused the change. using var _4 = ArrayBuilder<Document>.GetInstance(out var result); foreach (var task in tasks) result.AddRange(await task.ConfigureAwait(false)); return result.ToImmutable(); } /// <summary> /// Take all the changes made to a particular document and determine the text changes caused by each one. Take /// those individual text changes and attempt to merge them together in order into <paramref /// name="docIdToTextMerger"/>. /// </summary> private static async Task MergeTextChangesAsync( FixAllContext fixAllContext, ImmutableArray<Document> allChangedDocumentsInDiagnosticsOrder, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { var cancellationToken = fixAllContext.CancellationToken; // Now for each document that is changed, grab all the documents it was changed to (remember, many code // actions might have touched that document). Figure out the actual change, and then add that to the // interval tree of changes we're keeping track of for that document. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in allChangedDocumentsInDiagnosticsOrder.GroupBy(d => d.Id)) { var docId = group.Key; var allDocChanges = group.ToImmutableArray(); // If we don't have an text merger for this doc yet, create one to keep track of all the changes. if (!docIdToTextMerger.TryGetValue(docId, out var textMerger)) { var originalDocument = fixAllContext.Solution.GetRequiredDocument(docId); textMerger = new TextChangeMerger(originalDocument); docIdToTextMerger.Add(docId, textMerger); } // Process all document groups in parallel. For each group, merge all the doc changes into an // aggregated set of changes in the TextChangeMerger type. tasks.Add(Task.Run( async () => await textMerger.TryMergeChangesAsync(allDocChanges, cancellationToken).ConfigureAwait(false), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static Action<CodeAction, ImmutableArray<Diagnostic>> GetRegisterCodeFixAction( string? codeActionEquivalenceKey, ArrayBuilder<CodeAction> codeActions) { return (action, diagnostics) => { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); builder.Push(action); while (builder.Count > 0) { var currentAction = builder.Pop(); if (currentAction is { EquivalenceKey: var equivalenceKey } && codeActionEquivalenceKey == equivalenceKey) { lock (codeActions) codeActions.Add(currentAction); } foreach (var nestedAction in currentAction.NestedCodeActions) builder.Push(nestedAction); } }; } private static async Task<Solution> ApplyChangesAsync( Solution currentSolution, ImmutableArray<(DocumentId, TextChangeMerger)> docIdsAndMerger, CancellationToken cancellationToken) { foreach (var (documentId, textMerger) in docIdsAndMerger) { var newText = await textMerger.GetFinalMergedTextAsync(cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentText(documentId, newText); } return currentSolution; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Helper class for "Fix all occurrences" code fix providers. /// </summary> internal sealed class BatchFixAllProvider : FixAllProvider { public static readonly FixAllProvider Instance = new BatchFixAllProvider(); private BatchFixAllProvider() { } public override Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext) => DefaultFixAllProviderHelpers.GetFixAsync( FixAllContextHelper.GetDefaultFixAllTitle(fixAllContext), fixAllContext, FixAllContextsAsync); private async Task<Solution?> FixAllContextsAsync( FixAllContext originalFixAllContext, ImmutableArray<FixAllContext> fixAllContexts) { var cancellationToken = originalFixAllContext.CancellationToken; var progressTracker = originalFixAllContext.GetProgressTracker(); progressTracker.Description = FixAllContextHelper.GetDefaultFixAllTitle(originalFixAllContext); // We have 2*P + 1 pieces of work. Computing diagnostics and fixes/changes per context, and then one pass // applying fixes. progressTracker.AddItems(fixAllContexts.Length * 2 + 1); // Mapping from document to the cumulative text changes created for that document. var docIdToTextMerger = new Dictionary<DocumentId, TextChangeMerger>(); // Process each context one at a time, allowing us to dump most of the information we computed for each once // done with it. The only information we need to preserve is the data we store in docIdToTextMerger foreach (var fixAllContext in fixAllContexts) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project); await FixSingleContextAsync(fixAllContext, progressTracker, docIdToTextMerger).ConfigureAwait(false); } // Finally, merge in all text changes into the solution. We can't do this per-project as we have to have // process *all* diagnostics in the solution to find the changes made to all documents. using (progressTracker.ItemCompletedScope()) { if (docIdToTextMerger.Count == 0) return null; var currentSolution = originalFixAllContext.Solution; foreach (var group in docIdToTextMerger.GroupBy(kvp => kvp.Key.ProjectId)) currentSolution = await ApplyChangesAsync(currentSolution, group.SelectAsArray(kvp => (kvp.Key, kvp.Value)), cancellationToken).ConfigureAwait(false); return currentSolution; } } private static async Task FixSingleContextAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { // First, determine the diagnostics to fix for that context. var documentToDiagnostics = await DetermineDiagnosticsAsync(fixAllContext, progressTracker).ConfigureAwait(false); // Second, process all those diagnostics, merging the cumulative set of text changes per document into docIdToTextMerger. await AddDocumentChangesAsync(fixAllContext, progressTracker, docIdToTextMerger, documentToDiagnostics).ConfigureAwait(false); } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> DetermineDiagnosticsAsync(FixAllContext fixAllContext, IProgressTracker progressTracker) { using var _ = progressTracker.ItemCompletedScope(); var documentToDiagnostics = await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(false); var filtered = documentToDiagnostics.Where(kvp => { if (kvp.Key.Project != fixAllContext.Project) return false; if (fixAllContext.Document != null && fixAllContext.Document != kvp.Key) return false; return true; }); return filtered.ToImmutableDictionary(); } private static async Task AddDocumentChangesAsync( FixAllContext fixAllContext, IProgressTracker progressTracker, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger, ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentToDiagnostics) { using var _ = progressTracker.ItemCompletedScope(); // First, order the diagnostics so we process them in a consistent manner and get the same results given the // same input solution. var orderedDiagnostics = documentToDiagnostics.SelectMany(kvp => kvp.Value) .Where(d => d.Location.IsInSource) .OrderBy(d => d.Location.SourceTree!.FilePath) .ThenBy(d => d.Location.SourceSpan.Start) .ToImmutableArray(); // Now determine all the document changes caused from these diagnostics. var allChangedDocumentsInDiagnosticsOrder = await GetAllChangedDocumentsInDiagnosticsOrderAsync(fixAllContext, orderedDiagnostics).ConfigureAwait(false); // Finally, take all the changes made to each document and merge them together into docIdToTextMerger to // keep track of the total set of changes to any particular document. await MergeTextChangesAsync(fixAllContext, allChangedDocumentsInDiagnosticsOrder, docIdToTextMerger).ConfigureAwait(false); } /// <summary> /// Returns all the changed documents produced by fixing the list of provided <paramref /// name="orderedDiagnostics"/>. The documents will be returned such that fixed documents for a later /// diagnostic will appear later than those for an earlier diagnostic. /// </summary> private static async Task<ImmutableArray<Document>> GetAllChangedDocumentsInDiagnosticsOrderAsync( FixAllContext fixAllContext, ImmutableArray<Diagnostic> orderedDiagnostics) { var solution = fixAllContext.Solution; var cancellationToken = fixAllContext.CancellationToken; // Process each diagnostic, determine the code actions to fix it, then figure out the document changes // produced by that code action. using var _1 = ArrayBuilder<Task<ImmutableArray<Document>>>.GetInstance(out var tasks); foreach (var diagnostic in orderedDiagnostics) { var document = solution.GetRequiredDocument(diagnostic.Location.SourceTree!); cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(async () => { // Create a context that will add the reported code actions into this using var _2 = ArrayBuilder<CodeAction>.GetInstance(out var codeActions); var context = new CodeFixContext(document, diagnostic, GetRegisterCodeFixAction(fixAllContext.CodeActionEquivalenceKey, codeActions), cancellationToken); // Wait for the all the code actions to be reported for this diagnostic. var registerTask = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; await registerTask.ConfigureAwait(false); // Now, process each code action and find out all the document changes caused by it. using var _3 = ArrayBuilder<Document>.GetInstance(out var changedDocuments); foreach (var codeAction in codeActions) { var changedSolution = await codeAction.GetChangedSolutionInternalAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (changedSolution != null) { var changedDocumentIds = new SolutionChanges(changedSolution, solution).GetProjectChanges().SelectMany(p => p.GetChangedDocuments()); changedDocuments.AddRange(changedDocumentIds.Select(id => changedSolution.GetRequiredDocument(id))); } } return changedDocuments.ToImmutable(); }, cancellationToken)); } // Wait for all that work to finish. await Task.WhenAll(tasks).ConfigureAwait(false); // Flatten the set of changed documents. These will naturally still be ordered by the diagnostic that // caused the change. using var _4 = ArrayBuilder<Document>.GetInstance(out var result); foreach (var task in tasks) result.AddRange(await task.ConfigureAwait(false)); return result.ToImmutable(); } /// <summary> /// Take all the changes made to a particular document and determine the text changes caused by each one. Take /// those individual text changes and attempt to merge them together in order into <paramref /// name="docIdToTextMerger"/>. /// </summary> private static async Task MergeTextChangesAsync( FixAllContext fixAllContext, ImmutableArray<Document> allChangedDocumentsInDiagnosticsOrder, Dictionary<DocumentId, TextChangeMerger> docIdToTextMerger) { var cancellationToken = fixAllContext.CancellationToken; // Now for each document that is changed, grab all the documents it was changed to (remember, many code // actions might have touched that document). Figure out the actual change, and then add that to the // interval tree of changes we're keeping track of for that document. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in allChangedDocumentsInDiagnosticsOrder.GroupBy(d => d.Id)) { var docId = group.Key; var allDocChanges = group.ToImmutableArray(); // If we don't have an text merger for this doc yet, create one to keep track of all the changes. if (!docIdToTextMerger.TryGetValue(docId, out var textMerger)) { var originalDocument = fixAllContext.Solution.GetRequiredDocument(docId); textMerger = new TextChangeMerger(originalDocument); docIdToTextMerger.Add(docId, textMerger); } // Process all document groups in parallel. For each group, merge all the doc changes into an // aggregated set of changes in the TextChangeMerger type. tasks.Add(Task.Run( async () => await textMerger.TryMergeChangesAsync(allDocChanges, cancellationToken).ConfigureAwait(false), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static Action<CodeAction, ImmutableArray<Diagnostic>> GetRegisterCodeFixAction( string? codeActionEquivalenceKey, ArrayBuilder<CodeAction> codeActions) { return (action, diagnostics) => { using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); builder.Push(action); while (builder.Count > 0) { var currentAction = builder.Pop(); if (currentAction is { EquivalenceKey: var equivalenceKey } && codeActionEquivalenceKey == equivalenceKey) { lock (codeActions) codeActions.Add(currentAction); } foreach (var nestedAction in currentAction.NestedCodeActions) builder.Push(nestedAction); } }; } private static async Task<Solution> ApplyChangesAsync( Solution currentSolution, ImmutableArray<(DocumentId, TextChangeMerger)> docIdsAndMerger, CancellationToken cancellationToken) { foreach (var (documentId, textMerger) in docIdsAndMerger) { var newText = await textMerger.GetFinalMergedTextAsync(cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentText(documentId, newText); } return currentSolution; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal abstract partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> : IMoveDeclarationNearReferenceService where TService : AbstractMoveDeclarationNearReferenceService<TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> where TStatementSyntax : SyntaxNode where TLocalDeclarationStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { protected abstract bool IsMeaningfulBlock(SyntaxNode node); protected abstract bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock); protected abstract SyntaxNode GetVariableDeclaratorSymbolNode(TVariableDeclaratorSyntax variableDeclarator); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract SyntaxToken GetIdentifierOfVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract Task<bool> TypesAreCompatibleAsync(Document document, ILocalSymbol localSymbol, TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken); public async Task<bool> CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, node, cancellationToken).ConfigureAwait(false); return state != null; } private async Task<State> ComputeStateAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { if (node is not TLocalDeclarationStatementSyntax statement) { return null; } var state = await State.GenerateAsync((TService)this, document, statement, cancellationToken).ConfigureAwait(false); if (state == null) { return null; } if (state.IndexOfDeclarationStatementInInnermostBlock >= 0 && state.IndexOfDeclarationStatementInInnermostBlock == state.IndexOfFirstStatementAffectedInInnermostBlock - 1 && !await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false)) { // Declaration statement is already closest to the first reference // and they both cannot be merged into a single statement, so bail out. return null; } if (!CanMoveToBlock(state.LocalSymbol, state.OutermostBlock, state.InnermostBlock)) { return null; } return state; } public async Task<Document> MoveDeclarationNearReferenceAsync( Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, localDeclarationStatement, cancellationToken).ConfigureAwait(false); if (state == null) { return document; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var crossesMeaningfulBlock = CrossesMeaningfulBlock(state); var warningAnnotation = crossesMeaningfulBlock ? WarningAnnotation.Create(WorkspaceExtensionsResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning) : null; var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false); if (canMergeDeclarationAndAssignment) { editor.RemoveNode(state.DeclarationStatement); MergeDeclarationAndAssignment( document, state, editor, warningAnnotation); } else { var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count && state.OutermostBlockStatements[statementIndex + 1] == state.FirstStatementAffectedInInnermostBlock) { // Already at the correct location. return document; } editor.RemoveNode(state.DeclarationStatement); await MoveDeclarationToFirstReferenceAsync( document, state, editor, warningAnnotation, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private static async Task MoveDeclarationToFirstReferenceAsync( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation, CancellationToken cancellationToken) { // If we're not merging with an existing declaration, make the declaration semantically // explicit to improve the chances that it won't break code. var explicitDeclarationStatement = await Simplifier.ExpandAsync( state.DeclarationStatement, document, cancellationToken: cancellationToken).ConfigureAwait(false); // place the declaration above the first statement that references it. var declarationStatement = warningAnnotation == null ? explicitDeclarationStatement : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); var newNextStatement = state.FirstStatementAffectedInInnermostBlock; declarationStatement = declarationStatement.WithPrependedLeadingTrivia( bannerService.GetLeadingBlankLines(newNextStatement)); editor.InsertBefore( state.FirstStatementAffectedInInnermostBlock, declarationStatement); editor.ReplaceNode( newNextStatement, newNextStatement.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia( bannerService.GetTriviaAfterLeadingBlankLines(newNextStatement))); // Move leading whitespace from the declaration statement to the next statement. var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count) { var originalNextStatement = state.OutermostBlockStatements[statementIndex + 1]; editor.ReplaceNode( originalNextStatement, (current, generator) => current.WithAdditionalAnnotations(Formatter.Annotation).WithPrependedLeadingTrivia( bannerService.GetLeadingBlankLines(state.DeclarationStatement))); } } private static void MergeDeclarationAndAssignment( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation) { // Replace the first reference with a new declaration. var declarationStatement = CreateMergedDeclarationStatement(document, state); declarationStatement = warningAnnotation == null ? declarationStatement : declarationStatement.WithAdditionalAnnotations(warningAnnotation); var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); declarationStatement = declarationStatement.WithLeadingTrivia( GetMergedTrivia(bannerService, state.DeclarationStatement, state.FirstStatementAffectedInInnermostBlock)); editor.ReplaceNode( state.FirstStatementAffectedInInnermostBlock, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation)); } private static ImmutableArray<SyntaxTrivia> GetMergedTrivia( IFileBannerFactsService bannerService, TStatementSyntax statement1, TStatementSyntax statement2) { return bannerService.GetLeadingBlankLines(statement2).Concat( bannerService.GetTriviaAfterLeadingBlankLines(statement1)).Concat( bannerService.GetTriviaAfterLeadingBlankLines(statement2)); } private bool CrossesMeaningfulBlock(State state) { var blocks = state.InnermostBlock.GetAncestorsOrThis<SyntaxNode>(); foreach (var block in blocks) { if (block == state.OutermostBlock) { break; } if (IsMeaningfulBlock(block)) { return true; } } return false; } private async Task<bool> CanMergeDeclarationAndAssignmentAsync( Document document, State state, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(state.VariableDeclarator); if (initializer == null || syntaxFacts.IsLiteralExpression(syntaxFacts.GetValueOfEqualsValueClause(initializer))) { var firstStatement = state.FirstStatementAffectedInInnermostBlock; if (syntaxFacts.IsSimpleAssignmentStatement(firstStatement)) { syntaxFacts.GetPartsOfAssignmentStatement(firstStatement, out var left, out var right); if (syntaxFacts.IsIdentifierName(left)) { var localSymbol = state.LocalSymbol; var name = syntaxFacts.GetIdentifierOfSimpleName(left).ValueText; if (syntaxFacts.StringComparer.Equals(name, localSymbol.Name)) { return await TypesAreCompatibleAsync( document, localSymbol, state.DeclarationStatement, right, cancellationToken).ConfigureAwait(false); } } } } return false; } private static TLocalDeclarationStatementSyntax CreateMergedDeclarationStatement( Document document, State state) { var generator = document.GetLanguageService<SyntaxGeneratorInternal>(); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfAssignmentStatement( state.FirstStatementAffectedInInnermostBlock, out var _, out var operatorToken, out var right); return state.DeclarationStatement.ReplaceNode( state.VariableDeclarator, generator.WithInitializer( state.VariableDeclarator.WithoutTrailingTrivia(), generator.EqualsValueClause(operatorToken, right)) .WithTrailingTrivia(state.VariableDeclarator.GetTrailingTrivia())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal abstract partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> : IMoveDeclarationNearReferenceService where TService : AbstractMoveDeclarationNearReferenceService<TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> where TStatementSyntax : SyntaxNode where TLocalDeclarationStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { protected abstract bool IsMeaningfulBlock(SyntaxNode node); protected abstract bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock); protected abstract SyntaxNode GetVariableDeclaratorSymbolNode(TVariableDeclaratorSyntax variableDeclarator); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract SyntaxToken GetIdentifierOfVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract Task<bool> TypesAreCompatibleAsync(Document document, ILocalSymbol localSymbol, TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken); public async Task<bool> CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, node, cancellationToken).ConfigureAwait(false); return state != null; } private async Task<State> ComputeStateAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { if (node is not TLocalDeclarationStatementSyntax statement) { return null; } var state = await State.GenerateAsync((TService)this, document, statement, cancellationToken).ConfigureAwait(false); if (state == null) { return null; } if (state.IndexOfDeclarationStatementInInnermostBlock >= 0 && state.IndexOfDeclarationStatementInInnermostBlock == state.IndexOfFirstStatementAffectedInInnermostBlock - 1 && !await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false)) { // Declaration statement is already closest to the first reference // and they both cannot be merged into a single statement, so bail out. return null; } if (!CanMoveToBlock(state.LocalSymbol, state.OutermostBlock, state.InnermostBlock)) { return null; } return state; } public async Task<Document> MoveDeclarationNearReferenceAsync( Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken) { var state = await ComputeStateAsync(document, localDeclarationStatement, cancellationToken).ConfigureAwait(false); if (state == null) { return document; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var crossesMeaningfulBlock = CrossesMeaningfulBlock(state); var warningAnnotation = crossesMeaningfulBlock ? WarningAnnotation.Create(WorkspaceExtensionsResources.Warning_colon_Declaration_changes_scope_and_may_change_meaning) : null; var canMergeDeclarationAndAssignment = await CanMergeDeclarationAndAssignmentAsync(document, state, cancellationToken).ConfigureAwait(false); if (canMergeDeclarationAndAssignment) { editor.RemoveNode(state.DeclarationStatement); MergeDeclarationAndAssignment( document, state, editor, warningAnnotation); } else { var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count && state.OutermostBlockStatements[statementIndex + 1] == state.FirstStatementAffectedInInnermostBlock) { // Already at the correct location. return document; } editor.RemoveNode(state.DeclarationStatement); await MoveDeclarationToFirstReferenceAsync( document, state, editor, warningAnnotation, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private static async Task MoveDeclarationToFirstReferenceAsync( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation, CancellationToken cancellationToken) { // If we're not merging with an existing declaration, make the declaration semantically // explicit to improve the chances that it won't break code. var explicitDeclarationStatement = await Simplifier.ExpandAsync( state.DeclarationStatement, document, cancellationToken: cancellationToken).ConfigureAwait(false); // place the declaration above the first statement that references it. var declarationStatement = warningAnnotation == null ? explicitDeclarationStatement : explicitDeclarationStatement.WithAdditionalAnnotations(warningAnnotation); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); var newNextStatement = state.FirstStatementAffectedInInnermostBlock; declarationStatement = declarationStatement.WithPrependedLeadingTrivia( bannerService.GetLeadingBlankLines(newNextStatement)); editor.InsertBefore( state.FirstStatementAffectedInInnermostBlock, declarationStatement); editor.ReplaceNode( newNextStatement, newNextStatement.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia( bannerService.GetTriviaAfterLeadingBlankLines(newNextStatement))); // Move leading whitespace from the declaration statement to the next statement. var statementIndex = state.OutermostBlockStatements.IndexOf(state.DeclarationStatement); if (statementIndex + 1 < state.OutermostBlockStatements.Count) { var originalNextStatement = state.OutermostBlockStatements[statementIndex + 1]; editor.ReplaceNode( originalNextStatement, (current, generator) => current.WithAdditionalAnnotations(Formatter.Annotation).WithPrependedLeadingTrivia( bannerService.GetLeadingBlankLines(state.DeclarationStatement))); } } private static void MergeDeclarationAndAssignment( Document document, State state, SyntaxEditor editor, SyntaxAnnotation warningAnnotation) { // Replace the first reference with a new declaration. var declarationStatement = CreateMergedDeclarationStatement(document, state); declarationStatement = warningAnnotation == null ? declarationStatement : declarationStatement.WithAdditionalAnnotations(warningAnnotation); var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); declarationStatement = declarationStatement.WithLeadingTrivia( GetMergedTrivia(bannerService, state.DeclarationStatement, state.FirstStatementAffectedInInnermostBlock)); editor.ReplaceNode( state.FirstStatementAffectedInInnermostBlock, declarationStatement.WithAdditionalAnnotations(Formatter.Annotation)); } private static ImmutableArray<SyntaxTrivia> GetMergedTrivia( IFileBannerFactsService bannerService, TStatementSyntax statement1, TStatementSyntax statement2) { return bannerService.GetLeadingBlankLines(statement2).Concat( bannerService.GetTriviaAfterLeadingBlankLines(statement1)).Concat( bannerService.GetTriviaAfterLeadingBlankLines(statement2)); } private bool CrossesMeaningfulBlock(State state) { var blocks = state.InnermostBlock.GetAncestorsOrThis<SyntaxNode>(); foreach (var block in blocks) { if (block == state.OutermostBlock) { break; } if (IsMeaningfulBlock(block)) { return true; } } return false; } private async Task<bool> CanMergeDeclarationAndAssignmentAsync( Document document, State state, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(state.VariableDeclarator); if (initializer == null || syntaxFacts.IsLiteralExpression(syntaxFacts.GetValueOfEqualsValueClause(initializer))) { var firstStatement = state.FirstStatementAffectedInInnermostBlock; if (syntaxFacts.IsSimpleAssignmentStatement(firstStatement)) { syntaxFacts.GetPartsOfAssignmentStatement(firstStatement, out var left, out var right); if (syntaxFacts.IsIdentifierName(left)) { var localSymbol = state.LocalSymbol; var name = syntaxFacts.GetIdentifierOfSimpleName(left).ValueText; if (syntaxFacts.StringComparer.Equals(name, localSymbol.Name)) { return await TypesAreCompatibleAsync( document, localSymbol, state.DeclarationStatement, right, cancellationToken).ConfigureAwait(false); } } } } return false; } private static TLocalDeclarationStatementSyntax CreateMergedDeclarationStatement( Document document, State state) { var generator = document.GetLanguageService<SyntaxGeneratorInternal>(); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfAssignmentStatement( state.FirstStatementAffectedInInnermostBlock, out var _, out var operatorToken, out var right); return state.DeclarationStatement.ReplaceNode( state.VariableDeclarator, generator.WithInitializer( state.VariableDeclarator.WithoutTrailingTrivia(), generator.EqualsValueClause(operatorToken, right)) .WithTrailingTrivia(state.VariableDeclarator.GetTrailingTrivia())); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.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.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using System.Linq; using static CodeFixHelpers; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIndexOperator), Shared] internal class CSharpUseIndexOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIndexOperatorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseIndexOperatorDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Process diagnostics from innermost to outermost in case any are nested. foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( node, (currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_index_operator, createChangedDocument, CSharpAnalyzersResources.Use_index_operator) { } } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using System.Linq; using static CodeFixHelpers; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIndexOperator), Shared] internal class CSharpUseIndexOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIndexOperatorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseIndexOperatorDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Process diagnostics from innermost to outermost in case any are nested. foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( node, (currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_index_operator, createChangedDocument, CSharpAnalyzersResources.Use_index_operator) { } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Shared/BuildClient.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.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Reflection; #if NET472 using System.Runtime; #else using System.Runtime.Loader; #endif using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CommandLine { internal delegate int CompileFunc(string[] arguments, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerAssemblyLoader); internal delegate Task<BuildResponse> CompileOnServerFunc(BuildRequest buildRequest, string pipeName, CancellationToken cancellationToken); internal readonly struct RunCompilationResult { internal static readonly RunCompilationResult Succeeded = new RunCompilationResult(CommonCompiler.Succeeded); internal static readonly RunCompilationResult Failed = new RunCompilationResult(CommonCompiler.Failed); internal int ExitCode { get; } internal bool RanOnServer { get; } internal RunCompilationResult(int exitCode, bool ranOnServer = false) { ExitCode = exitCode; RanOnServer = ranOnServer; } } /// <summary> /// Client class that handles communication to the server. /// </summary> internal sealed class BuildClient { internal static bool IsRunningOnWindows => Path.DirectorySeparatorChar == '\\'; private readonly RequestLanguage _language; private readonly CompileFunc _compileFunc; private readonly CompileOnServerFunc _compileOnServerFunc; /// <summary> /// When set it overrides all timeout values in milliseconds when communicating with the server. /// </summary> internal BuildClient(RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc) { _language = language; _compileFunc = compileFunc; _compileOnServerFunc = compileOnServerFunc; } /// <summary> /// Get the directory which contains the csc, vbc and VBCSCompiler clients. /// /// Historically this is referred to as the "client" directory but maybe better if it was /// called the "installation" directory. /// /// It is important that this method exist here and not on <see cref="BuildServerConnection"/>. This /// can only reliably be called from our executable projects and this file is only linked into /// those projects while <see cref="BuildServerConnection"/> is also included in the MSBuild /// task. /// </summary> public static string GetClientDirectory() => // VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the // location of the response files. // // BaseDirectory was mistakenly marked as potentially null in 3.1 // https://github.com/dotnet/runtime/pull/32486 AppDomain.CurrentDomain.BaseDirectory!; /// <summary> /// Returns the directory that contains mscorlib, or null when running on CoreCLR. /// </summary> public static string GetSystemSdkDirectory() { return RuntimeHostInfo.IsCoreClrRuntime ? null : RuntimeEnvironment.GetRuntimeDirectory(); } internal static int Run(IEnumerable<string> arguments, RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc) { var sdkDir = GetSystemSdkDirectory(); if (RuntimeHostInfo.IsCoreClrRuntime) { // Register encodings for console // https://github.com/dotnet/roslyn/issues/10785 System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); } var client = new BuildClient(language, compileFunc, compileOnServerFunc); var clientDir = GetClientDirectory(); var workingDir = Directory.GetCurrentDirectory(); var tempDir = BuildServerConnection.GetTempPath(workingDir); var buildPaths = new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir); var originalArguments = GetCommandLineArgs(arguments); return client.RunCompilation(originalArguments, buildPaths).ExitCode; } /// <summary> /// Run a compilation through the compiler server and print the output /// to the console. If the compiler server fails, run the fallback /// compiler. /// </summary> internal RunCompilationResult RunCompilation(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null, string pipeName = null) { textWriter = textWriter ?? Console.Out; var args = originalArguments.Select(arg => arg.Trim()).ToArray(); List<string> parsedArgs; bool hasShared; string keepAliveOpt; string errorMessageOpt; if (CommandLineParser.TryParseClientArgs( args, out parsedArgs, out hasShared, out keepAliveOpt, out string commandLinePipeName, out errorMessageOpt)) { pipeName ??= commandLinePipeName; } else { textWriter.WriteLine(errorMessageOpt); return RunCompilationResult.Failed; } if (hasShared) { pipeName = pipeName ?? BuildServerConnection.GetPipeName(buildPaths.ClientDirectory); var libDirectory = Environment.GetEnvironmentVariable("LIB"); var serverResult = RunServerCompilation(textWriter, parsedArgs, buildPaths, libDirectory, pipeName, keepAliveOpt); if (serverResult.HasValue) { Debug.Assert(serverResult.Value.RanOnServer); return serverResult.Value; } } // It's okay, and expected, for the server compilation to fail. In that case just fall // back to normal compilation. var exitCode = RunLocalCompilation(parsedArgs.ToArray(), buildPaths, textWriter); return new RunCompilationResult(exitCode); } private static bool TryEnableMulticoreJitting(out string errorMessage) { errorMessage = null; try { // Enable multi-core JITing // https://blogs.msdn.microsoft.com/dotnet/2012/10/18/an-easy-solution-for-improving-app-launch-performance/ var profileRoot = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RoslynCompiler", "ProfileOptimization"); var assemblyName = Assembly.GetExecutingAssembly().GetName(); var profileName = assemblyName.Name + assemblyName.Version + ".profile"; Directory.CreateDirectory(profileRoot); #if NET472 ProfileOptimization.SetProfileRoot(profileRoot); ProfileOptimization.StartProfile(profileName); #else AssemblyLoadContext.Default.SetProfileOptimizationRoot(profileRoot); AssemblyLoadContext.Default.StartProfileOptimization(profileName); #endif } catch (Exception e) { errorMessage = string.Format(CodeAnalysisResources.ExceptionEnablingMulticoreJit, e.Message); return false; } return true; } public Task<RunCompilationResult> RunCompilationAsync(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null) { var tcs = new TaskCompletionSource<RunCompilationResult>(); ThreadStart action = () => { try { var result = RunCompilation(originalArguments, buildPaths, textWriter); tcs.SetResult(result); } catch (Exception ex) { tcs.SetException(ex); } }; var thread = new Thread(action); thread.Start(); return tcs.Task; } private int RunLocalCompilation(string[] arguments, BuildPaths buildPaths, TextWriter textWriter) { var loader = new DefaultAnalyzerAssemblyLoader(); return _compileFunc(arguments, buildPaths, textWriter, loader); } public static CompileOnServerFunc GetCompileOnServerFunc(ICompilerServerLogger logger) => (buildRequest, pipeName, cancellationToken) => BuildServerConnection.RunServerBuildRequestAsync( buildRequest, pipeName, GetClientDirectory(), logger, cancellationToken); /// <summary> /// Runs the provided compilation on the server. If the compilation cannot be completed on the server then null /// will be returned. /// </summary> private RunCompilationResult? RunServerCompilation(TextWriter textWriter, List<string> arguments, BuildPaths buildPaths, string libDirectory, string pipeName, string keepAlive) { BuildResponse buildResponse; if (!AreNamedPipesSupported()) { return null; } try { var requestId = Guid.NewGuid(); var buildRequest = BuildServerConnection.CreateBuildRequest( requestId, _language, arguments, workingDirectory: buildPaths.WorkingDirectory, tempDirectory: buildPaths.TempDirectory, keepAlive: keepAlive, libDirectory: libDirectory); var buildResponseTask = _compileOnServerFunc( buildRequest, pipeName, cancellationToken: default); buildResponse = buildResponseTask.Result; Debug.Assert(buildResponse != null); if (buildResponse == null) { return null; } } catch (Exception) { return null; } switch (buildResponse.Type) { case BuildResponse.ResponseType.Completed: { var completedResponse = (CompletedBuildResponse)buildResponse; return ConsoleUtil.RunWithUtf8Output(completedResponse.Utf8Output, textWriter, tw => { tw.Write(completedResponse.Output); return new RunCompilationResult(completedResponse.ReturnCode, ranOnServer: true); }); } case BuildResponse.ResponseType.MismatchedVersion: case BuildResponse.ResponseType.IncorrectHash: case BuildResponse.ResponseType.Rejected: case BuildResponse.ResponseType.AnalyzerInconsistency: // Build could not be completed on the server. return null; default: // Will not happen with our server but hypothetically could be sent by a rogue server. Should // not let that block compilation. Debug.Assert(false); return null; } } private static IEnumerable<string> GetCommandLineArgs(IEnumerable<string> args) { if (UseNativeArguments()) { return GetCommandLineWindows(args); } return args; } private static bool UseNativeArguments() { if (!IsRunningOnWindows) { return false; } if (PlatformInformation.IsRunningOnMono) { return false; } if (RuntimeHostInfo.IsCoreClrRuntime) { // The native invoke ends up giving us both CoreRun and the exe file. // We've decided to ignore backcompat for CoreCLR, // and use the Main()-provided arguments // https://github.com/dotnet/roslyn/issues/6677 return false; } return true; } private static bool AreNamedPipesSupported() { if (!PlatformInformation.IsRunningOnMono) return true; IDisposable npcs = null; try { var testPipeName = $"mono-{Guid.NewGuid()}"; // Mono configurations without named pipe support will throw a PNSE at some point in this process. npcs = new NamedPipeClientStream(".", testPipeName, PipeDirection.InOut); npcs.Dispose(); return true; } catch (PlatformNotSupportedException) { if (npcs != null) { // Compensate for broken finalizer in older builds of mono // https://github.com/mono/mono/commit/2a731f29b065392ca9b44d6613abee2aa413a144 GC.SuppressFinalize(npcs); } return false; } } /// <summary> /// When running on Windows we can't take the command line which was provided to the /// Main method of the application. That will go through normal windows command line /// parsing which eliminates artifacts like quotes. This has the effect of normalizing /// the below command line options, which are semantically different, into the same /// value: /// /// /reference:a,b /// /reference:"a,b" /// /// To get the correct semantics here on Windows we parse the original command line /// provided to the process. /// </summary> private static IEnumerable<string> GetCommandLineWindows(IEnumerable<string> args) { IntPtr ptr = NativeMethods.GetCommandLine(); if (ptr == IntPtr.Zero) { return args; } // This memory is owned by the operating system hence we shouldn't (and can't) // free the memory. var commandLine = Marshal.PtrToStringUni(ptr); // The first argument will be the executable name hence we skip it. return CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: false).Skip(1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Reflection; #if NET472 using System.Runtime; #else using System.Runtime.Loader; #endif using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CommandLine { internal delegate int CompileFunc(string[] arguments, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerAssemblyLoader); internal delegate Task<BuildResponse> CompileOnServerFunc(BuildRequest buildRequest, string pipeName, CancellationToken cancellationToken); internal readonly struct RunCompilationResult { internal static readonly RunCompilationResult Succeeded = new RunCompilationResult(CommonCompiler.Succeeded); internal static readonly RunCompilationResult Failed = new RunCompilationResult(CommonCompiler.Failed); internal int ExitCode { get; } internal bool RanOnServer { get; } internal RunCompilationResult(int exitCode, bool ranOnServer = false) { ExitCode = exitCode; RanOnServer = ranOnServer; } } /// <summary> /// Client class that handles communication to the server. /// </summary> internal sealed class BuildClient { internal static bool IsRunningOnWindows => Path.DirectorySeparatorChar == '\\'; private readonly RequestLanguage _language; private readonly CompileFunc _compileFunc; private readonly CompileOnServerFunc _compileOnServerFunc; /// <summary> /// When set it overrides all timeout values in milliseconds when communicating with the server. /// </summary> internal BuildClient(RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc) { _language = language; _compileFunc = compileFunc; _compileOnServerFunc = compileOnServerFunc; } /// <summary> /// Get the directory which contains the csc, vbc and VBCSCompiler clients. /// /// Historically this is referred to as the "client" directory but maybe better if it was /// called the "installation" directory. /// /// It is important that this method exist here and not on <see cref="BuildServerConnection"/>. This /// can only reliably be called from our executable projects and this file is only linked into /// those projects while <see cref="BuildServerConnection"/> is also included in the MSBuild /// task. /// </summary> public static string GetClientDirectory() => // VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the // location of the response files. // // BaseDirectory was mistakenly marked as potentially null in 3.1 // https://github.com/dotnet/runtime/pull/32486 AppDomain.CurrentDomain.BaseDirectory!; /// <summary> /// Returns the directory that contains mscorlib, or null when running on CoreCLR. /// </summary> public static string GetSystemSdkDirectory() { return RuntimeHostInfo.IsCoreClrRuntime ? null : RuntimeEnvironment.GetRuntimeDirectory(); } internal static int Run(IEnumerable<string> arguments, RequestLanguage language, CompileFunc compileFunc, CompileOnServerFunc compileOnServerFunc) { var sdkDir = GetSystemSdkDirectory(); if (RuntimeHostInfo.IsCoreClrRuntime) { // Register encodings for console // https://github.com/dotnet/roslyn/issues/10785 System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); } var client = new BuildClient(language, compileFunc, compileOnServerFunc); var clientDir = GetClientDirectory(); var workingDir = Directory.GetCurrentDirectory(); var tempDir = BuildServerConnection.GetTempPath(workingDir); var buildPaths = new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir); var originalArguments = GetCommandLineArgs(arguments); return client.RunCompilation(originalArguments, buildPaths).ExitCode; } /// <summary> /// Run a compilation through the compiler server and print the output /// to the console. If the compiler server fails, run the fallback /// compiler. /// </summary> internal RunCompilationResult RunCompilation(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null, string pipeName = null) { textWriter = textWriter ?? Console.Out; var args = originalArguments.Select(arg => arg.Trim()).ToArray(); List<string> parsedArgs; bool hasShared; string keepAliveOpt; string errorMessageOpt; if (CommandLineParser.TryParseClientArgs( args, out parsedArgs, out hasShared, out keepAliveOpt, out string commandLinePipeName, out errorMessageOpt)) { pipeName ??= commandLinePipeName; } else { textWriter.WriteLine(errorMessageOpt); return RunCompilationResult.Failed; } if (hasShared) { pipeName = pipeName ?? BuildServerConnection.GetPipeName(buildPaths.ClientDirectory); var libDirectory = Environment.GetEnvironmentVariable("LIB"); var serverResult = RunServerCompilation(textWriter, parsedArgs, buildPaths, libDirectory, pipeName, keepAliveOpt); if (serverResult.HasValue) { Debug.Assert(serverResult.Value.RanOnServer); return serverResult.Value; } } // It's okay, and expected, for the server compilation to fail. In that case just fall // back to normal compilation. var exitCode = RunLocalCompilation(parsedArgs.ToArray(), buildPaths, textWriter); return new RunCompilationResult(exitCode); } private static bool TryEnableMulticoreJitting(out string errorMessage) { errorMessage = null; try { // Enable multi-core JITing // https://blogs.msdn.microsoft.com/dotnet/2012/10/18/an-easy-solution-for-improving-app-launch-performance/ var profileRoot = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RoslynCompiler", "ProfileOptimization"); var assemblyName = Assembly.GetExecutingAssembly().GetName(); var profileName = assemblyName.Name + assemblyName.Version + ".profile"; Directory.CreateDirectory(profileRoot); #if NET472 ProfileOptimization.SetProfileRoot(profileRoot); ProfileOptimization.StartProfile(profileName); #else AssemblyLoadContext.Default.SetProfileOptimizationRoot(profileRoot); AssemblyLoadContext.Default.StartProfileOptimization(profileName); #endif } catch (Exception e) { errorMessage = string.Format(CodeAnalysisResources.ExceptionEnablingMulticoreJit, e.Message); return false; } return true; } public Task<RunCompilationResult> RunCompilationAsync(IEnumerable<string> originalArguments, BuildPaths buildPaths, TextWriter textWriter = null) { var tcs = new TaskCompletionSource<RunCompilationResult>(); ThreadStart action = () => { try { var result = RunCompilation(originalArguments, buildPaths, textWriter); tcs.SetResult(result); } catch (Exception ex) { tcs.SetException(ex); } }; var thread = new Thread(action); thread.Start(); return tcs.Task; } private int RunLocalCompilation(string[] arguments, BuildPaths buildPaths, TextWriter textWriter) { var loader = new DefaultAnalyzerAssemblyLoader(); return _compileFunc(arguments, buildPaths, textWriter, loader); } public static CompileOnServerFunc GetCompileOnServerFunc(ICompilerServerLogger logger) => (buildRequest, pipeName, cancellationToken) => BuildServerConnection.RunServerBuildRequestAsync( buildRequest, pipeName, GetClientDirectory(), logger, cancellationToken); /// <summary> /// Runs the provided compilation on the server. If the compilation cannot be completed on the server then null /// will be returned. /// </summary> private RunCompilationResult? RunServerCompilation(TextWriter textWriter, List<string> arguments, BuildPaths buildPaths, string libDirectory, string pipeName, string keepAlive) { BuildResponse buildResponse; if (!AreNamedPipesSupported()) { return null; } try { var requestId = Guid.NewGuid(); var buildRequest = BuildServerConnection.CreateBuildRequest( requestId, _language, arguments, workingDirectory: buildPaths.WorkingDirectory, tempDirectory: buildPaths.TempDirectory, keepAlive: keepAlive, libDirectory: libDirectory); var buildResponseTask = _compileOnServerFunc( buildRequest, pipeName, cancellationToken: default); buildResponse = buildResponseTask.Result; Debug.Assert(buildResponse != null); if (buildResponse == null) { return null; } } catch (Exception) { return null; } switch (buildResponse.Type) { case BuildResponse.ResponseType.Completed: { var completedResponse = (CompletedBuildResponse)buildResponse; return ConsoleUtil.RunWithUtf8Output(completedResponse.Utf8Output, textWriter, tw => { tw.Write(completedResponse.Output); return new RunCompilationResult(completedResponse.ReturnCode, ranOnServer: true); }); } case BuildResponse.ResponseType.MismatchedVersion: case BuildResponse.ResponseType.IncorrectHash: case BuildResponse.ResponseType.Rejected: case BuildResponse.ResponseType.AnalyzerInconsistency: // Build could not be completed on the server. return null; default: // Will not happen with our server but hypothetically could be sent by a rogue server. Should // not let that block compilation. Debug.Assert(false); return null; } } private static IEnumerable<string> GetCommandLineArgs(IEnumerable<string> args) { if (UseNativeArguments()) { return GetCommandLineWindows(args); } return args; } private static bool UseNativeArguments() { if (!IsRunningOnWindows) { return false; } if (PlatformInformation.IsRunningOnMono) { return false; } if (RuntimeHostInfo.IsCoreClrRuntime) { // The native invoke ends up giving us both CoreRun and the exe file. // We've decided to ignore backcompat for CoreCLR, // and use the Main()-provided arguments // https://github.com/dotnet/roslyn/issues/6677 return false; } return true; } private static bool AreNamedPipesSupported() { if (!PlatformInformation.IsRunningOnMono) return true; IDisposable npcs = null; try { var testPipeName = $"mono-{Guid.NewGuid()}"; // Mono configurations without named pipe support will throw a PNSE at some point in this process. npcs = new NamedPipeClientStream(".", testPipeName, PipeDirection.InOut); npcs.Dispose(); return true; } catch (PlatformNotSupportedException) { if (npcs != null) { // Compensate for broken finalizer in older builds of mono // https://github.com/mono/mono/commit/2a731f29b065392ca9b44d6613abee2aa413a144 GC.SuppressFinalize(npcs); } return false; } } /// <summary> /// When running on Windows we can't take the command line which was provided to the /// Main method of the application. That will go through normal windows command line /// parsing which eliminates artifacts like quotes. This has the effect of normalizing /// the below command line options, which are semantically different, into the same /// value: /// /// /reference:a,b /// /reference:"a,b" /// /// To get the correct semantics here on Windows we parse the original command line /// provided to the process. /// </summary> private static IEnumerable<string> GetCommandLineWindows(IEnumerable<string> args) { IntPtr ptr = NativeMethods.GetCommandLine(); if (ptr == IntPtr.Zero) { return args; } // This memory is owned by the operating system hence we shouldn't (and can't) // free the memory. var commandLine = Marshal.PtrToStringUni(ptr); // The first argument will be the executable name hence we skip it. return CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: false).Skip(1); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Test/Core/Platform/Desktop/AppDomainAssemblyCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { /// <summary> /// This is a singleton per AppDomain which manages all of the assemblies which were ever loaded into it. /// </summary> internal sealed class AppDomainAssemblyCache { private static AppDomainAssemblyCache s_singleton; private static readonly object s_guard = new object(); // The key is the manifest module MVID, which is unique for each distinct assembly. private readonly Dictionary<Guid, Assembly> _assemblyCache = new Dictionary<Guid, Assembly>(); private readonly Dictionary<Guid, Assembly> _reflectionOnlyAssemblyCache = new Dictionary<Guid, Assembly>(); internal static AppDomainAssemblyCache GetOrCreate() { lock (s_guard) { if (s_singleton == null) { s_singleton = new AppDomainAssemblyCache(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyLoad += OnAssemblyLoad; } return s_singleton; } } private AppDomainAssemblyCache() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var cache = assembly.ReflectionOnly ? _assemblyCache : _reflectionOnlyAssemblyCache; cache.Add(assembly.ManifestModule.ModuleVersionId, assembly); } } internal Assembly GetOrDefault(ModuleDataId id, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(id.Mvid, out var assembly)) { return assembly; } return null; } } internal Assembly GetOrLoad(ModuleData moduleData, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(moduleData.Mvid, out var assembly)) { return assembly; } var loadedAssembly = DesktopRuntimeUtil.LoadAsAssembly(moduleData.SimpleName, moduleData.Image, reflectionOnly); // Validate the loaded assembly matches the value that we now have in the cache. if (!cache.TryGetValue(moduleData.Mvid, out assembly)) { throw new Exception($"Explicit assembly load didn't update the proper cache: '{moduleData.SimpleName}' ({moduleData.Mvid})"); } if (loadedAssembly != assembly) { throw new Exception("Cache entry doesn't match result of load"); } return assembly; } } private void OnAssemblyLoad(Assembly assembly) { // We need to add loaded assemblies to the cache in order to avoid loading them twice. // This is not just optimization. CLR isn't able to load the same assembly from multiple "locations". // Location for byte[] assemblies is the location of the assembly that invokes Assembly.Load. // PE verifier invokes load directly for the assembly being verified. If this assembly is also a dependency // of another assembly we verify our AssemblyResolve is invoked. If we didn't reuse the assembly already loaded // by PE verifier we would get an error from Assembly.Load. var cache = assembly.ReflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { var mvid = assembly.ManifestModule.ModuleVersionId; if (!cache.ContainsKey(mvid)) { cache.Add(mvid, assembly); } } } private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { GetOrCreate().OnAssemblyLoad(args.LoadedAssembly); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { /// <summary> /// This is a singleton per AppDomain which manages all of the assemblies which were ever loaded into it. /// </summary> internal sealed class AppDomainAssemblyCache { private static AppDomainAssemblyCache s_singleton; private static readonly object s_guard = new object(); // The key is the manifest module MVID, which is unique for each distinct assembly. private readonly Dictionary<Guid, Assembly> _assemblyCache = new Dictionary<Guid, Assembly>(); private readonly Dictionary<Guid, Assembly> _reflectionOnlyAssemblyCache = new Dictionary<Guid, Assembly>(); internal static AppDomainAssemblyCache GetOrCreate() { lock (s_guard) { if (s_singleton == null) { s_singleton = new AppDomainAssemblyCache(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyLoad += OnAssemblyLoad; } return s_singleton; } } private AppDomainAssemblyCache() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var cache = assembly.ReflectionOnly ? _assemblyCache : _reflectionOnlyAssemblyCache; cache.Add(assembly.ManifestModule.ModuleVersionId, assembly); } } internal Assembly GetOrDefault(ModuleDataId id, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(id.Mvid, out var assembly)) { return assembly; } return null; } } internal Assembly GetOrLoad(ModuleData moduleData, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(moduleData.Mvid, out var assembly)) { return assembly; } var loadedAssembly = DesktopRuntimeUtil.LoadAsAssembly(moduleData.SimpleName, moduleData.Image, reflectionOnly); // Validate the loaded assembly matches the value that we now have in the cache. if (!cache.TryGetValue(moduleData.Mvid, out assembly)) { throw new Exception($"Explicit assembly load didn't update the proper cache: '{moduleData.SimpleName}' ({moduleData.Mvid})"); } if (loadedAssembly != assembly) { throw new Exception("Cache entry doesn't match result of load"); } return assembly; } } private void OnAssemblyLoad(Assembly assembly) { // We need to add loaded assemblies to the cache in order to avoid loading them twice. // This is not just optimization. CLR isn't able to load the same assembly from multiple "locations". // Location for byte[] assemblies is the location of the assembly that invokes Assembly.Load. // PE verifier invokes load directly for the assembly being verified. If this assembly is also a dependency // of another assembly we verify our AssemblyResolve is invoked. If we didn't reuse the assembly already loaded // by PE verifier we would get an error from Assembly.Load. var cache = assembly.ReflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { var mvid = assembly.ManifestModule.ModuleVersionId; if (!cache.ContainsKey(mvid)) { cache.Add(mvid, assembly); } } } private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { GetOrCreate().OnAssemblyLoad(args.LoadedAssembly); } } } #endif
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/TestUtilities/Diagnostics/TestHostDiagnosticUpdateSource.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.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource { private readonly Workspace _workspace; public TestHostDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public override Workspace Workspace { get { return _workspace; } } public override int GetHashCode() => _workspace.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource { private readonly Workspace _workspace; public TestHostDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public override Workspace Workspace { get { return _workspace; } } public override int GetHashCode() => _workspace.GetHashCode(); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/Xaml/Impl/Features/Formatting/XamlFormattingOptions.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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal class XamlFormattingOptions { public bool InsertSpaces { get; set; } public int TabSize { get; set; } public IDictionary<string, object> OtherOptions { get; 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. #nullable disable using System.Collections.Generic; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal class XamlFormattingOptions { public bool InsertSpaces { get; set; } public int TabSize { get; set; } public IDictionary<string, object> OtherOptions { get; set; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/Syntax/LookupPosition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary> /// This class contains a variety of helper methods for determining whether a /// position is within the scope (and not just the span) of a node. In general, /// general, the scope extends from the first token up to, but not including, /// the last token. For example, the open brace of a block is within the scope /// of the block, but the close brace is not. /// </summary> internal static class LookupPosition { /// <summary> /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. /// </summary> internal static bool IsInBlock(int position, BlockSyntax? blockOpt) { return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken); } internal static bool IsInExpressionBody( int position, ArrowExpressionClauseSyntax? expressionBodyOpt, SyntaxToken semicolonToken) { return expressionBodyOpt != null && IsBeforeToken(position, expressionBodyOpt, semicolonToken); } private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt) { return IsInExpressionBody(position, exprOpt, semiOpt) || IsInBlock(position, blockOpt); } /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, PropertyDeclarationSyntax property) => IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken); /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, IndexerDeclarationSyntax indexer) => IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken); /// <summary> /// A position is inside an accessor body if it is inside the block or expression /// body. /// </summary> internal static bool IsInBody(int position, AccessorDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); /// <summary> /// A position is inside a body if it is inside the block or expression /// body. /// /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. A position is /// considered to be inside an expression body if it is on or after /// the '=>' and strictly before the semicolon. /// </summary> internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded) { return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded); } /// <summary> /// Returns true if position is within the given node and before the first excluded token. /// </summary> private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded) { return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart; } private static bool IsBeforeToken(int position, SyntaxToken firstExcluded) { return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart; } internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList) { int count = attributesSyntaxList.Count; if (count == 0) { return false; } var startToken = attributesSyntaxList[0].OpenBracketToken; var endToken = attributesSyntaxList[count - 1].CloseBracketToken; return IsBetweenTokens(position, startToken, endToken); } internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl) { var typeParameterListOpt = typeDecl.TypeParameterList; return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken); } internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl) { var parameterList = methodDecl.ParameterList; return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); } internal static bool IsInParameterList(int position, ParameterListSyntax parameterList) => parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken); internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); var body = methodDecl.Body; if (body == null) { return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken); } return IsBeforeToken(position, methodDecl, body.CloseBraceToken) || IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken); } internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl) { Debug.Assert(accessorDecl != null); var body = accessorDecl.Body; SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken; return IsBeforeToken(position, accessorDecl, lastToken); } internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl) { Debug.Assert(delegateDecl != null); return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken); } internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl) { Debug.Assert(typeDecl != null); return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return position >= namespaceDecl.SpanStart; } internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl) { Debug.Assert(constructorDecl != null); var initializerOpt = constructorDecl.Initializer; var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null; if (!hasBody) { var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null); return initializerOpt == null ? position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) : IsBetweenTokens(position, initializerOpt.ColonToken, nextToken); } return initializerOpt == null ? IsInBody(position, constructorDecl) : IsBetweenTokens(position, initializerOpt.ColonToken, constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken); } internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); Debug.Assert(IsInMethodDeclaration(position, methodDecl)); if (methodDecl.TypeParameterList == null) { // no type parameters => nothing can be in their scope return false; } // optimization for a common case - when position is in the ReturnType, we can see type parameters if (methodDecl.ReturnType.FullSpan.Contains(position)) { return true; } // Must be in the method, but not in an attribute on the method. if (IsInAttributeSpecification(position, methodDecl.AttributeLists)) { return false; } var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier; var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken(); var typeParams = methodDecl.TypeParameterList; var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken; // Scope does not include method name. return !IsBetweenTokens(position, firstNameToken, firstPostNameToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInStatementScope(int position, StatementSyntax statement) { Debug.Assert(statement != null); if (statement.Kind() == SyntaxKind.EmptyStatement) { return false; } // CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens, // but this is where it has special meaning. SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement); return firstIncludedToken != default(SyntaxToken) && IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement)); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the switch section (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section) { Debug.Assert(section != null); return section.Span.Contains(position); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause) { Debug.Assert(catchClause != null); return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause) { Debug.Assert(filterClause != null); return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken); } private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).OpenBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).BreakKeyword; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Keyword; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).ContinueKeyword; case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: return statement.GetFirstToken(); case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).DoKeyword; case SyntaxKind.EmptyStatement: return default(SyntaxToken); //The caller will have to check for this. case SyntaxKind.FixedStatement: return ((FixedStatementSyntax)statement).FixedKeyword; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.ForStatement: return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).GotoKeyword; case SyntaxKind.IfStatement: return ((IfStatementSyntax)statement).IfKeyword; case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)statement).Identifier; case SyntaxKind.LockStatement: return ((LockStatementSyntax)statement).LockKeyword; case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).ReturnKeyword; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).Expression.GetFirstToken(); case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).ThrowKeyword; case SyntaxKind.TryStatement: return ((TryStatementSyntax)statement).TryKeyword; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).UnsafeKeyword; case SyntaxKind.UsingStatement: return ((UsingStatementSyntax)statement).UsingKeyword; case SyntaxKind.WhileStatement: return ((WhileStatementSyntax)statement).WhileKeyword; case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).YieldKeyword; case SyntaxKind.LocalFunctionStatement: return statement.GetFirstToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).CloseBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).SemicolonToken; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)statement).SemicolonToken; case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).SemicolonToken; case SyntaxKind.EmptyStatement: return ((EmptyStatementSyntax)statement).SemicolonToken; case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).SemicolonToken; case SyntaxKind.FixedStatement: return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement); case SyntaxKind.ForStatement: return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).SemicolonToken; case SyntaxKind.IfStatement: IfStatementSyntax ifStmt = (IfStatementSyntax)statement; ElseClauseSyntax? elseOpt = ifStmt.Else; return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement); case SyntaxKind.LabeledStatement: return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement); case SyntaxKind.LockStatement: return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement); case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).SemicolonToken; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).CloseBraceToken; case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).SemicolonToken; case SyntaxKind.TryStatement: TryStatementSyntax tryStmt = (TryStatementSyntax)statement; FinallyClauseSyntax? finallyClause = tryStmt.Finally; if (finallyClause != null) { return finallyClause.Block.CloseBraceToken; } CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault(); if (lastCatch != null) { return lastCatch.Block.CloseBraceToken; } return tryStmt.Block.CloseBraceToken; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.UsingStatement: return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement); case SyntaxKind.WhileStatement: return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalFunctionStatement: LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement; if (localFunctionStmt.Body != null) return GetFirstExcludedToken(localFunctionStmt.Body); if (localFunctionStmt.SemicolonToken != default(SyntaxToken)) return localFunctionStmt.SemicolonToken; return localFunctionStmt.ParameterList.GetLastToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) { Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery()); SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (lambdaExpressionOrQueryNode.Kind()) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = simple.ArrowToken; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = parenthesized.ArrowToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode; body = anon.Block; firstIncluded = body.GetFirstToken(includeZeroWidth: true); break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken(); return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken()); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null ? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return IsBetweenTokens(position, firstIncluded, firstExcluded); } internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute) { return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary> /// This class contains a variety of helper methods for determining whether a /// position is within the scope (and not just the span) of a node. In general, /// general, the scope extends from the first token up to, but not including, /// the last token. For example, the open brace of a block is within the scope /// of the block, but the close brace is not. /// </summary> internal static class LookupPosition { /// <summary> /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. /// </summary> internal static bool IsInBlock(int position, BlockSyntax? blockOpt) { return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken); } internal static bool IsInExpressionBody( int position, ArrowExpressionClauseSyntax? expressionBodyOpt, SyntaxToken semicolonToken) { return expressionBodyOpt != null && IsBeforeToken(position, expressionBodyOpt, semicolonToken); } private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt) { return IsInExpressionBody(position, exprOpt, semiOpt) || IsInBlock(position, blockOpt); } /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, PropertyDeclarationSyntax property) => IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken); /// <summary> /// A position is inside a property body only if it is inside an expression body. /// All block bodies for properties are part of the accessor declaration (a type /// of BaseMethodDeclaration), not the property declaration. /// </summary> internal static bool IsInBody(int position, IndexerDeclarationSyntax indexer) => IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken); /// <summary> /// A position is inside an accessor body if it is inside the block or expression /// body. /// </summary> internal static bool IsInBody(int position, AccessorDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); /// <summary> /// A position is inside a body if it is inside the block or expression /// body. /// /// A position is considered to be inside a block if it is on or after /// the open brace and strictly before the close brace. A position is /// considered to be inside an expression body if it is on or after /// the '=>' and strictly before the semicolon. /// </summary> internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method) => IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken); internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded) { return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded); } /// <summary> /// Returns true if position is within the given node and before the first excluded token. /// </summary> private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded) { return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart; } private static bool IsBeforeToken(int position, SyntaxToken firstExcluded) { return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart; } internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList) { int count = attributesSyntaxList.Count; if (count == 0) { return false; } var startToken = attributesSyntaxList[0].OpenBracketToken; var endToken = attributesSyntaxList[count - 1].CloseBracketToken; return IsBetweenTokens(position, startToken, endToken); } internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl) { var typeParameterListOpt = typeDecl.TypeParameterList; return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken); } internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl) { var parameterList = methodDecl.ParameterList; return IsBeforeToken(position, parameterList, parameterList.CloseParenToken); } internal static bool IsInParameterList(int position, ParameterListSyntax parameterList) => parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken); internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); var body = methodDecl.Body; if (body == null) { return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken); } return IsBeforeToken(position, methodDecl, body.CloseBraceToken) || IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken); } internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl) { Debug.Assert(accessorDecl != null); var body = accessorDecl.Body; SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken; return IsBeforeToken(position, accessorDecl, lastToken); } internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl) { Debug.Assert(delegateDecl != null); return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken); } internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl) { Debug.Assert(typeDecl != null); return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken); } internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl) { Debug.Assert(namespaceDecl != null); return position >= namespaceDecl.SpanStart; } internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl) { Debug.Assert(constructorDecl != null); var initializerOpt = constructorDecl.Initializer; var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null; if (!hasBody) { var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null); return initializerOpt == null ? position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) : IsBetweenTokens(position, initializerOpt.ColonToken, nextToken); } return initializerOpt == null ? IsInBody(position, constructorDecl) : IsBetweenTokens(position, initializerOpt.ColonToken, constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken); } internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl) { Debug.Assert(methodDecl != null); Debug.Assert(IsInMethodDeclaration(position, methodDecl)); if (methodDecl.TypeParameterList == null) { // no type parameters => nothing can be in their scope return false; } // optimization for a common case - when position is in the ReturnType, we can see type parameters if (methodDecl.ReturnType.FullSpan.Contains(position)) { return true; } // Must be in the method, but not in an attribute on the method. if (IsInAttributeSpecification(position, methodDecl.AttributeLists)) { return false; } var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier; var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken(); var typeParams = methodDecl.TypeParameterList; var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken; // Scope does not include method name. return !IsBetweenTokens(position, firstNameToken, firstPostNameToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInStatementScope(int position, StatementSyntax statement) { Debug.Assert(statement != null); if (statement.Kind() == SyntaxKind.EmptyStatement) { return false; } // CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens, // but this is where it has special meaning. SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement); return firstIncludedToken != default(SyntaxToken) && IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement)); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the switch section (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section) { Debug.Assert(section != null); return section.Span.Contains(position); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause) { Debug.Assert(catchClause != null); return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken); } /// <remarks> /// Used to determine whether it would be appropriate to use the binder for the statement (if any). /// Not used to determine whether the position is syntactically within the statement. /// </remarks> internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause) { Debug.Assert(filterClause != null); return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken); } private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).OpenBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).BreakKeyword; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Keyword; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).ContinueKeyword; case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: return statement.GetFirstToken(); case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).DoKeyword; case SyntaxKind.EmptyStatement: return default(SyntaxToken); //The caller will have to check for this. case SyntaxKind.FixedStatement: return ((FixedStatementSyntax)statement).FixedKeyword; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.ForStatement: return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken(); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).GotoKeyword; case SyntaxKind.IfStatement: return ((IfStatementSyntax)statement).IfKeyword; case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)statement).Identifier; case SyntaxKind.LockStatement: return ((LockStatementSyntax)statement).LockKeyword; case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).ReturnKeyword; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).Expression.GetFirstToken(); case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).ThrowKeyword; case SyntaxKind.TryStatement: return ((TryStatementSyntax)statement).TryKeyword; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).UnsafeKeyword; case SyntaxKind.UsingStatement: return ((UsingStatementSyntax)statement).UsingKeyword; case SyntaxKind.WhileStatement: return ((WhileStatementSyntax)statement).WhileKeyword; case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).YieldKeyword; case SyntaxKind.LocalFunctionStatement: return statement.GetFirstToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return ((BlockSyntax)statement).CloseBraceToken; case SyntaxKind.BreakStatement: return ((BreakStatementSyntax)statement).SemicolonToken; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.ContinueStatement: return ((ContinueStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)statement).SemicolonToken; case SyntaxKind.DoStatement: return ((DoStatementSyntax)statement).SemicolonToken; case SyntaxKind.EmptyStatement: return ((EmptyStatementSyntax)statement).SemicolonToken; case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).SemicolonToken; case SyntaxKind.FixedStatement: return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement); case SyntaxKind.ForStatement: return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return ((GotoStatementSyntax)statement).SemicolonToken; case SyntaxKind.IfStatement: IfStatementSyntax ifStmt = (IfStatementSyntax)statement; ElseClauseSyntax? elseOpt = ifStmt.Else; return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement); case SyntaxKind.LabeledStatement: return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement); case SyntaxKind.LockStatement: return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement); case SyntaxKind.ReturnStatement: return ((ReturnStatementSyntax)statement).SemicolonToken; case SyntaxKind.SwitchStatement: return ((SwitchStatementSyntax)statement).CloseBraceToken; case SyntaxKind.ThrowStatement: return ((ThrowStatementSyntax)statement).SemicolonToken; case SyntaxKind.TryStatement: TryStatementSyntax tryStmt = (TryStatementSyntax)statement; FinallyClauseSyntax? finallyClause = tryStmt.Finally; if (finallyClause != null) { return finallyClause.Block.CloseBraceToken; } CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault(); if (lastCatch != null) { return lastCatch.Block.CloseBraceToken; } return tryStmt.Block.CloseBraceToken; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken; case SyntaxKind.UsingStatement: return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement); case SyntaxKind.WhileStatement: return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return ((YieldStatementSyntax)statement).SemicolonToken; case SyntaxKind.LocalFunctionStatement: LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement; if (localFunctionStmt.Body != null) return GetFirstExcludedToken(localFunctionStmt.Body); if (localFunctionStmt.SemicolonToken != default(SyntaxToken)) return localFunctionStmt.SemicolonToken; return localFunctionStmt.ParameterList.GetLastToken(); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode) { Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery()); SyntaxToken firstIncluded; CSharpSyntaxNode body; switch (lambdaExpressionOrQueryNode.Kind()) { case SyntaxKind.SimpleLambdaExpression: SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = simple.ArrowToken; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode; firstIncluded = parenthesized.ArrowToken; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode; body = anon.Block; firstIncluded = body.GetFirstToken(includeZeroWidth: true); break; default: // OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that. firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken(); return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken()); } var bodyStatement = body as StatementSyntax; var firstExcluded = bodyStatement != null ? GetFirstExcludedToken(bodyStatement) : (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null); return IsBetweenTokens(position, firstIncluded, firstExcluded); } internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute) { return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/CSharp/Portable/NameTupleElement/CSharpNameTupleElementCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.NameTupleElement; namespace Microsoft.CodeAnalysis.CSharp.NameTupleElement { [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.NameTupleElement), Shared] internal class CSharpNameTupleElementCodeRefactoringProvider : AbstractNameTupleElementCodeRefactoringProvider<ArgumentSyntax, TupleExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpNameTupleElementCodeRefactoringProvider() { } protected override ArgumentSyntax WithName(ArgumentSyntax argument, string argumentName) => argument.WithNameColon(SyntaxFactory.NameColon(argumentName.ToIdentifierName())); } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.NameTupleElement; namespace Microsoft.CodeAnalysis.CSharp.NameTupleElement { [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.NameTupleElement), Shared] internal class CSharpNameTupleElementCodeRefactoringProvider : AbstractNameTupleElementCodeRefactoringProvider<ArgumentSyntax, TupleExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpNameTupleElementCodeRefactoringProvider() { } protected override ArgumentSyntax WithName(ArgumentSyntax argument, string argumentName) => argument.WithNameColon(SyntaxFactory.NameColon(argumentName.ToIdentifierName())); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/CommandLine/SarifV1ErrorLoggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Microsoft.CodeAnalysis.DiagnosticExtensions; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { [Trait(Traits.Feature, Traits.Features.SarifErrorLogging)] public class SarifV1ErrorLoggerTests : SarifErrorLoggerTests { protected override string ErrorLogQualifier => string.Empty; internal override string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = @" ""results"": [ ] } ] }"; return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void NoDiagnostics() { NoDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = string.Format(@" ""results"": [ {{ ""ruleId"": ""CS5001"", ""level"": ""error"", ""message"": ""Program does not contain a static 'Main' method suitable for an entry point"" }}, {{ ""ruleId"": ""CS0169"", ""level"": ""warning"", ""message"": ""The field 'C.x' is never used"", ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 4, ""startColumn"": 17, ""endLine"": 4, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""rules"": {{ ""CS0169"": {{ ""id"": ""CS0169"", ""shortDescription"": ""Field is never used"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, ""CS5001"": {{ ""id"": ""CS5001"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnostics() { SimpleCompilerDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = string.Format(@" ""results"": [ {{ ""ruleId"": ""CS5001"", ""level"": ""error"", ""message"": ""Program does not contain a static 'Main' method suitable for an entry point"" }}, {{ ""ruleId"": ""CS0169"", ""level"": ""warning"", ""message"": ""The field 'C.x' is never used"", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 5, ""startColumn"": 17, ""endLine"": 5, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""rules"": {{ ""CS0169"": {{ ""id"": ""CS0169"", ""shortDescription"": ""Field is never used"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, ""CS5001"": {{ ""id"": ""CS5001"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnosticsSuppressed() { SimpleCompilerDiagnosticsSuppressedImpl(); } internal override string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogResultsAndRulesText(cmd.Compilation); return expectedHeader + expectedIssues; } internal override string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(cmd.Compilation); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void AnalyzerDiagnosticsWithAndWithoutLocation() { AnalyzerDiagnosticsWithAndWithoutLocationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithJustification() { AnalyzerDiagnosticsSuppressedWithJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithMissingJustification() { AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithEmptyJustification() { AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithNullJustification() { AnalyzerDiagnosticsSuppressedWithNullJustificationImpl(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Microsoft.CodeAnalysis.DiagnosticExtensions; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { [Trait(Traits.Feature, Traits.Features.SarifErrorLogging)] public class SarifV1ErrorLoggerTests : SarifErrorLoggerTests { protected override string ErrorLogQualifier => string.Empty; internal override string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = @" ""results"": [ ] } ] }"; return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void NoDiagnostics() { NoDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = string.Format(@" ""results"": [ {{ ""ruleId"": ""CS5001"", ""level"": ""error"", ""message"": ""Program does not contain a static 'Main' method suitable for an entry point"" }}, {{ ""ruleId"": ""CS0169"", ""level"": ""warning"", ""message"": ""The field 'C.x' is never used"", ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 4, ""startColumn"": 17, ""endLine"": 4, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""rules"": {{ ""CS0169"": {{ ""id"": ""CS0169"", ""shortDescription"": ""Field is never used"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, ""CS5001"": {{ ""id"": ""CS5001"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnostics() { SimpleCompilerDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = string.Format(@" ""results"": [ {{ ""ruleId"": ""CS5001"", ""level"": ""error"", ""message"": ""Program does not contain a static 'Main' method suitable for an entry point"" }}, {{ ""ruleId"": ""CS0169"", ""level"": ""warning"", ""message"": ""The field 'C.x' is never used"", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 5, ""startColumn"": 17, ""endLine"": 5, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""rules"": {{ ""CS0169"": {{ ""id"": ""CS0169"", ""shortDescription"": ""Field is never used"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, ""CS5001"": {{ ""id"": ""CS5001"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnosticsSuppressed() { SimpleCompilerDiagnosticsSuppressedImpl(); } internal override string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogResultsAndRulesText(cmd.Compilation); return expectedHeader + expectedIssues; } internal override string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification) { var expectedHeader = GetExpectedErrorLogHeader(cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(cmd.Compilation); return expectedHeader + expectedIssues; } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void AnalyzerDiagnosticsWithAndWithoutLocation() { AnalyzerDiagnosticsWithAndWithoutLocationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithJustification() { AnalyzerDiagnosticsSuppressedWithJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithMissingJustification() { AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithEmptyJustification() { AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl(); } [ConditionalFact(typeof(WindowsOnly))] public void AnalyzerDiagnosticsSuppressedWithNullJustification() { AnalyzerDiagnosticsSuppressedWithNullJustificationImpl(); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Analyzers/Core/Analyzers/ValidateFormatString/ValidateFormatStringOption.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ValidateFormatString { internal class ValidateFormatStringOption { public static PerLanguageOption2<bool> ReportInvalidPlaceholdersInStringDotFormatCalls = new( nameof(ValidateFormatStringOption), nameof(ReportInvalidPlaceholdersInStringDotFormatCalls), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.WarnOnInvalidStringDotFormatCalls")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ValidateFormatString { internal class ValidateFormatStringOption { public static PerLanguageOption2<bool> ReportInvalidPlaceholdersInStringDotFormatCalls = new( nameof(ValidateFormatStringOption), nameof(ReportInvalidPlaceholdersInStringDotFormatCalls), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.WarnOnInvalidStringDotFormatCalls")); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharpTest2/Recommendations/PartialKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class PartialKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInPartialType() { await VerifyKeywordAsync( @"partial class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInPartialClass() { await VerifyKeywordAsync( @"partial class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInPartialClass() { await VerifyKeywordAsync( @"partial class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttributeInPartialClass() { await VerifyKeywordAsync( @"partial class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsidePartialStruct() { await VerifyKeywordAsync( @"partial struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsidePartialClass() { await VerifyKeywordAsync( @"partial class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtual() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverride() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedReadOnly() { await VerifyKeywordAsync(@"class C { readonly $$"); } [WorkItem(578075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578075")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() { await VerifyKeywordAsync(@"partial class C { async $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class PartialKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInPartialType() { await VerifyKeywordAsync( @"partial class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInPartialClass() { await VerifyKeywordAsync( @"partial class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInPartialClass() { await VerifyKeywordAsync( @"partial class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttributeInPartialClass() { await VerifyKeywordAsync( @"partial class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsidePartialStruct() { await VerifyKeywordAsync( @"partial struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsidePartialClass() { await VerifyKeywordAsync( @"partial class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtual() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverride() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedReadOnly() { await VerifyKeywordAsync(@"class C { readonly $$"); } [WorkItem(578075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578075")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() { await VerifyKeywordAsync(@"partial class C { async $$"); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTestBase : WorkspaceTestBase { protected const string MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; protected static void AssertFailures(MSBuildWorkspace workspace, params string[] expectedFailures) { AssertEx.Equal(expectedFailures, workspace.Diagnostics.Where(d => d.Kind == WorkspaceDiagnosticKind.Failure).Select(d => d.Message)); } protected async Task AssertCSCompilationOptionsAsync<T>(T expected, Func<CS.CSharpCompilationOptions, T> actual) { var options = await LoadCSharpCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertCSParseOptionsAsync<T>(T expected, Func<CS.CSharpParseOptions, T> actual) { var options = await LoadCSharpParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBCompilationOptionsAsync<T>(T expected, Func<VB.VisualBasicCompilationOptions, T> actual) { var options = await LoadVisualBasicCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBParseOptionsAsync<T>(T expected, Func<VB.VisualBasicParseOptions, T> actual) { var options = await LoadVisualBasicParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task<CS.CSharpCompilationOptions> LoadCSharpCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpCompilationOptions)project.CompilationOptions; } } protected async Task<CS.CSharpParseOptions> LoadCSharpParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpParseOptions)project.ParseOptions; } } protected async Task<VB.VisualBasicCompilationOptions> LoadVisualBasicCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicCompilationOptions)project.CompilationOptions; } } protected async Task<VB.VisualBasicParseOptions> LoadVisualBasicParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicParseOptions)project.ParseOptions; } } protected static int GetMethodInsertionPoint(VB.Syntax.ClassBlockSyntax classBlock) { if (classBlock.Implements.Count > 0) { return classBlock.Implements[classBlock.Implements.Count - 1].FullSpan.End; } else if (classBlock.Inherits.Count > 0) { return classBlock.Inherits[classBlock.Inherits.Count - 1].FullSpan.End; } else { return classBlock.BlockStatement.FullSpan.End; } } protected async Task PrepareCrossLanguageProjectWithEmittedMetadataAsync() { // Now try variant of CSharpProject that has an emitted assembly CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ForEmittedOutput)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.NotNull(p1.OutputFilePath); Assert.Equal("EmittedCSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); // if the assembly doesn't already exist, emit it now if (!File.Exists(p1.OutputFilePath)) { var c1 = await p1.GetCompilationAsync(); var result = c1.Emit(p1.OutputFilePath); Assert.True(result.Success); } } } protected async Task<Solution> SolutionAsync(params IBuilder[] inputs) { var files = GetSolutionFiles(inputs); CreateFiles(files); var solutionFileName = files.First(t => t.fileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)).fileName; solutionFileName = GetSolutionFileName(solutionFileName); using (var workspace = CreateMSBuildWorkspace()) { return await workspace.OpenSolutionAsync(solutionFileName); } } protected static MSBuildWorkspace CreateMSBuildWorkspace(params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties)); } protected static MSBuildWorkspace CreateMSBuildWorkspace(HostServices hostServices, params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties), hostServices); } private static Dictionary<string, string> CreateProperties((string key, string value)[] additionalProperties) { var properties = new Dictionary<string, string>(); foreach (var (k, v) in additionalProperties) { properties.Add(k, v); } return properties; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTestBase : WorkspaceTestBase { protected const string MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; protected static void AssertFailures(MSBuildWorkspace workspace, params string[] expectedFailures) { AssertEx.Equal(expectedFailures, workspace.Diagnostics.Where(d => d.Kind == WorkspaceDiagnosticKind.Failure).Select(d => d.Message)); } protected async Task AssertCSCompilationOptionsAsync<T>(T expected, Func<CS.CSharpCompilationOptions, T> actual) { var options = await LoadCSharpCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertCSParseOptionsAsync<T>(T expected, Func<CS.CSharpParseOptions, T> actual) { var options = await LoadCSharpParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBCompilationOptionsAsync<T>(T expected, Func<VB.VisualBasicCompilationOptions, T> actual) { var options = await LoadVisualBasicCompilationOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task AssertVBParseOptionsAsync<T>(T expected, Func<VB.VisualBasicParseOptions, T> actual) { var options = await LoadVisualBasicParseOptionsAsync(); Assert.Equal(expected, actual(options)); } protected async Task<CS.CSharpCompilationOptions> LoadCSharpCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpCompilationOptions)project.CompilationOptions; } } protected async Task<CS.CSharpParseOptions> LoadCSharpParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); return (CS.CSharpParseOptions)project.ParseOptions; } } protected async Task<VB.VisualBasicCompilationOptions> LoadVisualBasicCompilationOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicCompilationOptions)project.CompilationOptions; } } protected async Task<VB.VisualBasicParseOptions> LoadVisualBasicParseOptionsAsync() { var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); return (VB.VisualBasicParseOptions)project.ParseOptions; } } protected static int GetMethodInsertionPoint(VB.Syntax.ClassBlockSyntax classBlock) { if (classBlock.Implements.Count > 0) { return classBlock.Implements[classBlock.Implements.Count - 1].FullSpan.End; } else if (classBlock.Inherits.Count > 0) { return classBlock.Inherits[classBlock.Inherits.Count - 1].FullSpan.End; } else { return classBlock.BlockStatement.FullSpan.End; } } protected async Task PrepareCrossLanguageProjectWithEmittedMetadataAsync() { // Now try variant of CSharpProject that has an emitted assembly CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ForEmittedOutput)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using (var workspace = CreateMSBuildWorkspace()) { var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.NotNull(p1.OutputFilePath); Assert.Equal("EmittedCSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); // if the assembly doesn't already exist, emit it now if (!File.Exists(p1.OutputFilePath)) { var c1 = await p1.GetCompilationAsync(); var result = c1.Emit(p1.OutputFilePath); Assert.True(result.Success); } } } protected async Task<Solution> SolutionAsync(params IBuilder[] inputs) { var files = GetSolutionFiles(inputs); CreateFiles(files); var solutionFileName = files.First(t => t.fileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)).fileName; solutionFileName = GetSolutionFileName(solutionFileName); using (var workspace = CreateMSBuildWorkspace()) { return await workspace.OpenSolutionAsync(solutionFileName); } } protected static MSBuildWorkspace CreateMSBuildWorkspace(params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties)); } protected static MSBuildWorkspace CreateMSBuildWorkspace(HostServices hostServices, params (string key, string value)[] additionalProperties) { return MSBuildWorkspace.Create(CreateProperties(additionalProperties), hostServices); } private static Dictionary<string, string> CreateProperties((string key, string value)[] additionalProperties) { var properties = new Dictionary<string, string>(); foreach (var (k, v) in additionalProperties) { properties.Add(k, v); } return properties; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Diagnostics; using System.Runtime.Serialization; namespace Microsoft.VisualStudio.Debugger { // // Summary: // Base exception class for all exceptions within this API. [DebuggerDisplay("\\{DkmException Code={Code,h}\\}")] [Serializable] public class DkmException : ApplicationException { private readonly DkmExceptionCode _code; // // Summary: // Create a new exception instance. To enable native-interop scenarios, this exception // system is error code based, so there is no exception string. // // Parameters: // code: // The HRESULT code for this exception. Using HRESULT values that are defined outside // the range of this enumerator are acceptable, but not encouraged. public DkmException(DkmExceptionCode code) { _code = code; } protected DkmException(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } // // Summary: // Provides the DkmExcepionCode for this exception public DkmExceptionCode Code { get { return _code; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Diagnostics; using System.Runtime.Serialization; namespace Microsoft.VisualStudio.Debugger { // // Summary: // Base exception class for all exceptions within this API. [DebuggerDisplay("\\{DkmException Code={Code,h}\\}")] [Serializable] public class DkmException : ApplicationException { private readonly DkmExceptionCode _code; // // Summary: // Create a new exception instance. To enable native-interop scenarios, this exception // system is error code based, so there is no exception string. // // Parameters: // code: // The HRESULT code for this exception. Using HRESULT values that are defined outside // the range of this enumerator are acceptable, but not encouraged. public DkmException(DkmExceptionCode code) { _code = code; } protected DkmException(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } // // Summary: // Provides the DkmExcepionCode for this exception public DkmExceptionCode Code { get { return _code; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/Core/Portable/Operations/BasicBlockKind.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.FlowAnalysis { /// <summary> /// <see cref="BasicBlock"/> kind. /// </summary> public enum BasicBlockKind { /// <summary> /// Indicates an entry block for a <see cref="ControlFlowGraph"/>, /// which is always the first block in <see cref="ControlFlowGraph.Blocks"/>. /// </summary> Entry, /// <summary> /// Indicates an exit block for a <see cref="ControlFlowGraph"/>, /// which is always the last block in <see cref="ControlFlowGraph.Blocks"/>. /// </summary> Exit, /// <summary> /// Indicates an intermediate block for a <see cref="ControlFlowGraph"/>. /// </summary> Block } }
// Licensed to the .NET Foundation under one or more 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.FlowAnalysis { /// <summary> /// <see cref="BasicBlock"/> kind. /// </summary> public enum BasicBlockKind { /// <summary> /// Indicates an entry block for a <see cref="ControlFlowGraph"/>, /// which is always the first block in <see cref="ControlFlowGraph.Blocks"/>. /// </summary> Entry, /// <summary> /// Indicates an exit block for a <see cref="ControlFlowGraph"/>, /// which is always the last block in <see cref="ControlFlowGraph.Blocks"/>. /// </summary> Exit, /// <summary> /// Indicates an intermediate block for a <see cref="ControlFlowGraph"/>. /// </summary> Block } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); private CompilationVerifier CompileAndVerify(CSharpTestSource src, string? expectedOutput = null) => base.CompileAndVerify(new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.Regular9, // init-only fails verification verify: Verification.Skipped); [Fact] public void GeneratedConstructor() { var comp = CreateCompilation(@"record C(int x, string y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var y = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, y.Type.SpecialType); Assert.Equal("y", y.Name); } [Fact] public void GeneratedConstructorDefaultValues() { var comp = CreateCompilation(@"record C<T>(int x, T t = default);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Arity); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(0, ctor.Arity); Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var t = ctor.Parameters[1]; Assert.Equal(c.TypeParameters[0], t.Type); Assert.Equal("t", t.Name); } [Fact] public void RecordExistingConstructor1() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, string b) { } }"); comp.VerifyDiagnostics( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, string b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12), // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, string b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[2]; Assert.Equal(2, ctor.ParameterCount); var a = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, a.Type.SpecialType); Assert.Equal("a", a.Name); var b = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, b.Type.SpecialType); Assert.Equal("b", b.Name); } [Fact] public void RecordExistingConstructor01() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, int b) // overload { } }"); comp.VerifyDiagnostics( // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) // overload Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctors = c.GetMembers(".ctor"); Assert.Equal(3, ctors.Length); foreach (MethodSymbol ctor in ctors) { if (ctor.ParameterCount == 2) { var p1 = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, p1.Type.SpecialType); var p2 = ctor.Parameters[1]; if (ctor is SynthesizedRecordConstructor) { Assert.Equal("x", p1.Name); Assert.Equal("y", p2.Name); Assert.Equal(SpecialType.System_String, p2.Type.SpecialType); } else { Assert.Equal("a", p1.Name); Assert.Equal("b", p2.Name); Assert.Equal(SpecialType.System_Int32, p2.Type.SpecialType); } } else { Assert.Equal(1, ctor.ParameterCount); Assert.True(c.Equals(ctor.Parameters[0].Type, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void GeneratedProperties() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var x = (SourcePropertySymbolBase)c.GetProperty("x"); Assert.NotNull(x.GetMethod); Assert.Equal(MethodKind.PropertyGet, x.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.False(x.IsReadOnly); Assert.False(x.IsWriteOnly); Assert.False(x.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, x.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, x.ContainingType); Assert.Equal(c, x.ContainingSymbol); var backing = x.BackingField; Assert.Equal(x, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); var getAccessor = x.GetMethod; Assert.Equal(x, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); Assert.Equal(Accessibility.Public, getAccessor.DeclaredAccessibility); var setAccessor = x.SetMethod; Assert.Equal(x, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); var y = (SourcePropertySymbolBase)c.GetProperty("y"); Assert.NotNull(y.GetMethod); Assert.Equal(MethodKind.PropertyGet, y.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, y.Type.SpecialType); Assert.False(y.IsReadOnly); Assert.False(y.IsWriteOnly); Assert.False(y.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, y.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, y.ContainingType); Assert.Equal(c, y.ContainingSymbol); backing = y.BackingField; Assert.Equal(y, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); getAccessor = y.GetMethod; Assert.Equal(y, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); setAccessor = y.SetMethod; Assert.Equal(y, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); } [Fact] public void RecordEquals_01() { var comp = CreateCompilation(@" record C(int X, int Y) { public bool Equals(C c) => throw null; public override bool Equals(object o) => false; } "); comp.VerifyDiagnostics( // (4,17): error CS8872: 'C.Equals(C)' must allow overriding because the containing record is not sealed. // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("C.Equals(C)").WithLocation(4, 17), // (4,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(4, 17), // (5,26): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object o) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(5, 26) ); comp = CreateCompilation(@" record C { public int Equals(object o) => throw null; } record D : C { } "); comp.VerifyDiagnostics( // (4,16): warning CS0114: 'C.Equals(object)' hides inherited member 'object.Equals(object)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Equals(object o) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Equals").WithArguments("C.Equals(object)", "object.Equals(object)").WithLocation(4, 16), // (4,16): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public int Equals(object o) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(4, 16) ); CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); Console.WriteLine(c.Equals(c)); } public virtual bool Equals(C c) => false; }", expectedOutput: "False").VerifyDiagnostics( // (10,25): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(C c) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(10, 25) ); } [Fact] public void RecordEquals_02() { CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(1, 1); var c2 = new C(1, 1); Console.WriteLine(c.Equals(c)); Console.WriteLine(c.Equals(c2)); } }", expectedOutput: @"True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_03() { var verifier = CompileAndVerify(@" using System; sealed record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } public bool Equals(C c) => X == c.X && Y == c.Y; }", expectedOutput: @"True False").VerifyDiagnostics( // (13,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => X == c.X && Y == c.Y; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(13, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: call ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""int C.X.get"" IL_0006: ldarg.1 IL_0007: callvirt ""int C.X.get"" IL_000c: bne.un.s IL_001d IL_000e: ldarg.0 IL_000f: call ""int C.Y.get"" IL_0014: ldarg.1 IL_0015: callvirt ""int C.Y.get"" IL_001a: ceq IL_001c: ret IL_001d: ldc.i4.0 IL_001e: ret }"); } [Fact] public void RecordEquals_04() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"True False").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_06() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { var c = new C(0, 0); object c2 = null; C c3 = null; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False False").VerifyDiagnostics(); } [Fact] public void RecordEquals_07() { var verifier = CompileAndVerify(@" using System; record C(int[] X, string Y) { public static void Main() { var arr = new[] {1, 2}; var c = new C(arr, ""abc""); var c2 = new C(new[] {1, 2}, ""abc""); var c3 = new C(arr, ""abc""); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False True").VerifyDiagnostics(); } [Fact] public void RecordEquals_08() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z; public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""int C.Z"" IL_0055: ldarg.1 IL_0056: ldfld ""int C.Z"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void RecordEquals_09() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z { get; set; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_10() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static int Z; public static void Main() { var c = new C(1, 2); C.Z = 3; var c2 = new C(1, 2); C.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); C.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_11() { var verifier = CompileAndVerify(@" using System; using System.Collections.Generic; record C(int X, int Y) { static Dictionary<C, int> s_dict = new Dictionary<C, int>(); public int Z { get => s_dict[this]; set => s_dict[this] = value; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_12() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { private event Action E; public static void Main() { var c = new C(1, 2); c.E = () => { }; var c2 = new C(1, 2); c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""System.Action C.E"" IL_0055: ldarg.1 IL_0056: ldfld ""System.Action C.E"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void RecordClone1() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ret }"); } [Fact] public void RecordClone2_0() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { x = other.x; y = other.y; } }"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: callvirt ""int C.x.get"" IL_000d: call ""void C.x.init"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: callvirt ""int C.y.get"" IL_0019: call ""void C.y.init"" IL_001e: ret } "); } [Fact] public void RecordClone2_0_WithThisInitializer() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : this(other.x, other.y) { } }"); comp.VerifyDiagnostics( // (4,25): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C other) : this(other.x, other.y) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(4, 25) ); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_1() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_2() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : base() { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44782, "https://github.com/dotnet/roslyn/issues/44782")] public void RecordClone3() { var comp = CreateCompilation(@" using System; public record C(int x, int y) { public event Action E; public int Z; public int W = 123; }"); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 67 (0x43) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""System.Action C.E"" IL_0025: stfld ""System.Action C.E"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Z"" IL_0031: stfld ""int C.Z"" IL_0036: ldarg.0 IL_0037: ldarg.1 IL_0038: ldfld ""int C.W"" IL_003d: stfld ""int C.W"" IL_0042: ret } "); } [Fact] public void NominalRecordEquals() { var verifier = CompileAndVerify(@" using System; record C { private int X; private int Y { get; set; } private event Action E; public static void Main() { var c = new C { X = 1, Y = 2 }; c.E = () => { }; var c2 = new C { X = 1, Y = 2 }; c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics( // (5,17): warning CS0414: The field 'C.X' is assigned but its value is never used // private int X; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(5, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.X"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.X"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""System.Action C.E"" IL_0055: ldarg.1 IL_0056: ldfld ""System.Action C.E"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void PositionalAndNominalSameEquals() { var v1 = CompileAndVerify(@" using System; record C(int X, string Y) { public event Action E; } ").VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var v2 = CompileAndVerify(@" using System; record C { public int X { get; } public string Y { get; } public event Action E; }").VerifyDiagnostics( // (7,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(7, 25) ); Assert.Equal(v1.VisualizeIL("C.Equals(C)"), v2.VisualizeIL("C.Equals(C)")); Assert.Equal(v1.VisualizeIL("C.Equals(object)"), v2.VisualizeIL("C.Equals(object)")); } [Fact] public void NominalRecordMembers() { var comp = CreateCompilation(@" #nullable enable record C { public int X { get; init; } public string Y { get; init; } }"); var members = comp.GlobalNamespace.GetTypeMember("C").GetMembers(); AssertEx.Equal(new[] { "System.Type! C.EqualityContract.get", "System.Type! C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X { get; init; }", "System.Int32 C.X.get", "void C.X.init", "System.String! C.<Y>k__BackingField", "System.String! C.Y { get; init; }", "System.String! C.Y.get", "void C.Y.init", "System.String! C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder! builder)", "System.Boolean C.operator !=(C? left, C? right)", "System.Boolean C.operator ==(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C! C." + WellKnownMemberNames.CloneMethodName + "()", "C.C(C! original)", "C.C()", }, members.Select(m => m.ToTestDisplayString(includeNonNullable: true))); } [Fact] public void PartialTypes_01() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X, int Y) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X, int Y) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X, int Y)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_02() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_03() { var src = @" partial record C { public int X = 1; } partial record C(int Y); partial record C { public int Z { get; } = 2; }"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stfld ""int C.X"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.2 IL_0010: stfld ""int C.<Z>k__BackingField"" IL_0015: ldarg.0 IL_0016: call ""object..ctor()"" IL_001b: ret }"); } [Fact] public void PartialTypes_04_PartialBeforeModifiers() { var src = @" partial public record C { } "; CreateCompilation(src).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record C Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void DataClassAndStruct() { var src = @" data class C1 { } data class C2(int X, int Y); data struct S1 { } data struct S2(int X, int Y);"; var comp = CreateCompilation(src, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (3,14): error CS8805: Program using top-level statements must be an executable. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int X, int Y);").WithLocation(3, 14), // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(2, 1), // (3,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(3, 1), // (3,14): error CS1514: { expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS1513: } expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS8803: Top-level statements must precede namespace and type declarations. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int X, int Y);").WithLocation(3, 14), // (3,14): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(3, 14), // (3,15): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(3, 15), // (3,15): error CS0165: Use of unassigned local variable 'X' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(3, 15), // (3,22): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(3, 22), // (3,22): error CS0165: Use of unassigned local variable 'Y' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(3, 22), // (4,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(4, 1), // (5,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(5, 1), // (5,15): error CS1514: { expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS1513: } expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(5, 15), // (5,16): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(5, 16), // (5,16): error CS0165: Use of unassigned local variable 'X' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(5, 16), // (5,20): error CS0128: A local variable or function named 'X' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "X").WithArguments("X").WithLocation(5, 20), // (5,23): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(5, 23), // (5,23): error CS0165: Use of unassigned local variable 'Y' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(5, 23), // (5,27): error CS0128: A local variable or function named 'Y' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Y").WithArguments("Y").WithLocation(5, 27) ); } [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] [Fact] public void ClassInheritingFromRecord() { var src = @" abstract record AbstractRecord {} class SomeClass : AbstractRecord {}"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,19): error CS8865: Only records may inherit from records. // class SomeClass : AbstractRecord {} Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "AbstractRecord").WithLocation(3, 19) ); } [Fact] public void RecordInheritance() { var src = @" class A { } record B : A { } record C : B { } class D : C { } interface E : C { } struct F : C { } enum G : C { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(3, 8), // (3,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record B : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (5,11): error CS8865: Only records may inherit from records. // class D : C { } Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "C").WithLocation(5, 11), // (6,15): error CS0527: Type 'C' in interface list is not an interface // interface E : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(6, 15), // (7,12): error CS0527: Type 'C' in interface list is not an interface // struct F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(7, 12), // (8,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum G : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(8, 10) ); } [Theory] [InlineData(true)] [InlineData(false)] public void RecordInheritance2(bool emitReference) { var src = @" public class A { } public record B { } public record C : B { }"; var comp = CreateCompilation(src); var src2 = @" record D : C { } record E : A { } interface F : C { } struct G : C { } enum H : C { } "; var comp2 = CreateCompilation(src2, parseOptions: TestOptions.Regular9, references: new[] { emitReference ? comp.EmitToImageReference() : comp.ToMetadataReference() }); comp2.VerifyDiagnostics( // (3,8): error CS0115: 'E.EqualityContract': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'E.Equals(A?)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.Equals(A?)").WithLocation(3, 8), // (3,8): error CS0115: 'E.PrintMembers(StringBuilder)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record E : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record E : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (4,15): error CS0527: Type 'C' in interface list is not an interface // interface F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(4, 15), // (5,12): error CS0527: Type 'C' in interface list is not an interface // struct G : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(5, 12), // (6,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum H : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(6, 10) ); } [Fact] public void GenericRecord() { var src = @" using System; record A<T> { public T Prop { get; init; } } record B : A<int>; record C<T>(T Prop2) : A<T>; class P { public static void Main() { var a = new A<int>() { Prop = 1 }; var a2 = a with { Prop = 2 }; Console.WriteLine(a.Prop + "" "" + a2.Prop); var b = new B() { Prop = 3 }; var b2 = b with { Prop = 4 }; Console.WriteLine(b.Prop + "" "" + b2.Prop); var c = new C<int>(5) { Prop = 6 }; var c2 = c with { Prop = 7, Prop2 = 8 }; Console.WriteLine(c.Prop + "" "" + c.Prop2); Console.WriteLine(c2.Prop2 + "" "" + c2.Prop); } }"; CompileAndVerify(src, expectedOutput: @" 1 2 3 4 6 5 8 7").VerifyDiagnostics(); } [Fact] public void RecordCloneSymbol() { var src = @" record R; record R2 : R"; var comp = CreateCompilation(src); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.False(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); } [Fact] public void AbstractRecordClone() { var src = @" abstract record R; abstract record R2 : R; record R3 : R2; abstract record R4 : R3; record R5 : R4; class C { public static void Main() { R r = new R3(); r = r with { }; R4 r4 = new R5(); r4 = r4 with { }; } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); Assert.Equal("R R." + WellKnownMemberNames.CloneMethodName + "()", clone.ToTestDisplayString()); Assert.True(clone.IsImplicitlyDeclared); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.True(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R2." + WellKnownMemberNames.CloneMethodName + "()", clone2.ToTestDisplayString()); Assert.True(clone2.IsImplicitlyDeclared); var r3 = comp.GlobalNamespace.GetTypeMember("R3"); var clone3 = (MethodSymbol)r3.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone3.IsOverride); Assert.False(clone3.IsVirtual); Assert.False(clone3.IsAbstract); Assert.Equal(0, clone3.ParameterCount); Assert.Equal(0, clone3.Arity); Assert.True(clone3.OverriddenMethod.Equals(clone2, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R3." + WellKnownMemberNames.CloneMethodName + "()", clone3.ToTestDisplayString()); Assert.True(clone3.IsImplicitlyDeclared); var r4 = comp.GlobalNamespace.GetTypeMember("R4"); var clone4 = (MethodSymbol)r4.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone4.IsOverride); Assert.False(clone4.IsVirtual); Assert.True(clone4.IsAbstract); Assert.Equal(0, clone4.ParameterCount); Assert.Equal(0, clone4.Arity); Assert.True(clone4.OverriddenMethod.Equals(clone3, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R4." + WellKnownMemberNames.CloneMethodName + "()", clone4.ToTestDisplayString()); Assert.True(clone4.IsImplicitlyDeclared); var r5 = comp.GlobalNamespace.GetTypeMember("R5"); var clone5 = (MethodSymbol)r5.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone5.IsOverride); Assert.False(clone5.IsVirtual); Assert.False(clone5.IsAbstract); Assert.Equal(0, clone5.ParameterCount); Assert.Equal(0, clone5.Arity); Assert.True(clone5.OverriddenMethod.Equals(clone4, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R5." + WellKnownMemberNames.CloneMethodName + "()", clone5.ToTestDisplayString()); Assert.True(clone5.IsImplicitlyDeclared); var verifier = CompileAndVerify(comp, expectedOutput: "", verify: Verification.Passes).VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: newobj ""R3..ctor()"" IL_0005: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000a: pop IL_000b: newobj ""R5..ctor()"" IL_0010: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: castclass ""R4"" IL_001a: pop IL_001b: ret }"); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithEventImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { event Action E1; } public record R1 : I1 { public event Action E1 { add { } remove { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithPropertyImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action P1 { get; set; } } public record R1 : I1 { public Action P1 { get; set; } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithMethodImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action M1(); } public record R1 : I1 { public Action M1() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void MergeInitializers_01() { var src = @" record C(int X) { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_02() { var src1 = @" partial record C(int X) { } "; var src2 = @" partial record C { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_03() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { Y = 22, X = 11 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { Y = 22, X = 11 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_04() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { } "; var src3 = @" partial record C { public int Z = 33; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2 + src3, expectedOutput: "C { Y = 22, X = 11, Z = 33 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2, src3 }, expectedOutput: "C { Y = 22, X = 11, Z = 33 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_05() { var src1 = @" partial record C(int X) { public int U = 44; } "; var src2 = @" partial record C { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { X = 11, U = 44, Y = 22 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { X = 11, U = 44, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_06() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { public int U = 44; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { Y = 22, X = 11, U = 44 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { Y = 22, X = 11, U = 44 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_07() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { public int U = 44; } "; var src3 = @" partial record C { public int Z = 33; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2 + src3, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2, src3 }, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); private CompilationVerifier CompileAndVerify(CSharpTestSource src, string? expectedOutput = null) => base.CompileAndVerify(new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.Regular9, // init-only fails verification verify: Verification.Skipped); [Fact] public void GeneratedConstructor() { var comp = CreateCompilation(@"record C(int x, string y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var y = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, y.Type.SpecialType); Assert.Equal("y", y.Name); } [Fact] public void GeneratedConstructorDefaultValues() { var comp = CreateCompilation(@"record C<T>(int x, T t = default);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Arity); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(0, ctor.Arity); Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var t = ctor.Parameters[1]; Assert.Equal(c.TypeParameters[0], t.Type); Assert.Equal("t", t.Name); } [Fact] public void RecordExistingConstructor1() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, string b) { } }"); comp.VerifyDiagnostics( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, string b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12), // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, string b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[2]; Assert.Equal(2, ctor.ParameterCount); var a = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, a.Type.SpecialType); Assert.Equal("a", a.Name); var b = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, b.Type.SpecialType); Assert.Equal("b", b.Name); } [Fact] public void RecordExistingConstructor01() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, int b) // overload { } }"); comp.VerifyDiagnostics( // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) // overload Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctors = c.GetMembers(".ctor"); Assert.Equal(3, ctors.Length); foreach (MethodSymbol ctor in ctors) { if (ctor.ParameterCount == 2) { var p1 = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, p1.Type.SpecialType); var p2 = ctor.Parameters[1]; if (ctor is SynthesizedRecordConstructor) { Assert.Equal("x", p1.Name); Assert.Equal("y", p2.Name); Assert.Equal(SpecialType.System_String, p2.Type.SpecialType); } else { Assert.Equal("a", p1.Name); Assert.Equal("b", p2.Name); Assert.Equal(SpecialType.System_Int32, p2.Type.SpecialType); } } else { Assert.Equal(1, ctor.ParameterCount); Assert.True(c.Equals(ctor.Parameters[0].Type, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void GeneratedProperties() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var x = (SourcePropertySymbolBase)c.GetProperty("x"); Assert.NotNull(x.GetMethod); Assert.Equal(MethodKind.PropertyGet, x.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.False(x.IsReadOnly); Assert.False(x.IsWriteOnly); Assert.False(x.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, x.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, x.ContainingType); Assert.Equal(c, x.ContainingSymbol); var backing = x.BackingField; Assert.Equal(x, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); var getAccessor = x.GetMethod; Assert.Equal(x, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); Assert.Equal(Accessibility.Public, getAccessor.DeclaredAccessibility); var setAccessor = x.SetMethod; Assert.Equal(x, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); var y = (SourcePropertySymbolBase)c.GetProperty("y"); Assert.NotNull(y.GetMethod); Assert.Equal(MethodKind.PropertyGet, y.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, y.Type.SpecialType); Assert.False(y.IsReadOnly); Assert.False(y.IsWriteOnly); Assert.False(y.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, y.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, y.ContainingType); Assert.Equal(c, y.ContainingSymbol); backing = y.BackingField; Assert.Equal(y, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); getAccessor = y.GetMethod; Assert.Equal(y, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); setAccessor = y.SetMethod; Assert.Equal(y, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); } [Fact] public void RecordEquals_01() { var comp = CreateCompilation(@" record C(int X, int Y) { public bool Equals(C c) => throw null; public override bool Equals(object o) => false; } "); comp.VerifyDiagnostics( // (4,17): error CS8872: 'C.Equals(C)' must allow overriding because the containing record is not sealed. // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("C.Equals(C)").WithLocation(4, 17), // (4,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(4, 17), // (5,26): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object o) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(5, 26) ); comp = CreateCompilation(@" record C { public int Equals(object o) => throw null; } record D : C { } "); comp.VerifyDiagnostics( // (4,16): warning CS0114: 'C.Equals(object)' hides inherited member 'object.Equals(object)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Equals(object o) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Equals").WithArguments("C.Equals(object)", "object.Equals(object)").WithLocation(4, 16), // (4,16): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public int Equals(object o) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(4, 16) ); CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); Console.WriteLine(c.Equals(c)); } public virtual bool Equals(C c) => false; }", expectedOutput: "False").VerifyDiagnostics( // (10,25): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(C c) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(10, 25) ); } [Fact] public void RecordEquals_02() { CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(1, 1); var c2 = new C(1, 1); Console.WriteLine(c.Equals(c)); Console.WriteLine(c.Equals(c2)); } }", expectedOutput: @"True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_03() { var verifier = CompileAndVerify(@" using System; sealed record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } public bool Equals(C c) => X == c.X && Y == c.Y; }", expectedOutput: @"True False").VerifyDiagnostics( // (13,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => X == c.X && Y == c.Y; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(13, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: call ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""int C.X.get"" IL_0006: ldarg.1 IL_0007: callvirt ""int C.X.get"" IL_000c: bne.un.s IL_001d IL_000e: ldarg.0 IL_000f: call ""int C.Y.get"" IL_0014: ldarg.1 IL_0015: callvirt ""int C.Y.get"" IL_001a: ceq IL_001c: ret IL_001d: ldc.i4.0 IL_001e: ret }"); } [Fact] public void RecordEquals_04() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"True False").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_06() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { var c = new C(0, 0); object c2 = null; C c3 = null; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False False").VerifyDiagnostics(); } [Fact] public void RecordEquals_07() { var verifier = CompileAndVerify(@" using System; record C(int[] X, string Y) { public static void Main() { var arr = new[] {1, 2}; var c = new C(arr, ""abc""); var c2 = new C(new[] {1, 2}, ""abc""); var c3 = new C(arr, ""abc""); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False True").VerifyDiagnostics(); } [Fact] public void RecordEquals_08() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z; public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""int C.Z"" IL_0055: ldarg.1 IL_0056: ldfld ""int C.Z"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void RecordEquals_09() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z { get; set; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_10() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static int Z; public static void Main() { var c = new C(1, 2); C.Z = 3; var c2 = new C(1, 2); C.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); C.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_11() { var verifier = CompileAndVerify(@" using System; using System.Collections.Generic; record C(int X, int Y) { static Dictionary<C, int> s_dict = new Dictionary<C, int>(); public int Z { get => s_dict[this]; set => s_dict[this] = value; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 77 (0x4d) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_004b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0049 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0049 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0049 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: ret IL_0049: ldc.i4.0 IL_004a: ret IL_004b: ldc.i4.1 IL_004c: ret }"); } [Fact] public void RecordEquals_12() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { private event Action E; public static void Main() { var c = new C(1, 2); c.E = () => { }; var c2 = new C(1, 2); c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""System.Action C.E"" IL_0055: ldarg.1 IL_0056: ldfld ""System.Action C.E"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void RecordClone1() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ret }"); } [Fact] public void RecordClone2_0() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { x = other.x; y = other.y; } }"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: callvirt ""int C.x.get"" IL_000d: call ""void C.x.init"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: callvirt ""int C.y.get"" IL_0019: call ""void C.y.init"" IL_001e: ret } "); } [Fact] public void RecordClone2_0_WithThisInitializer() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : this(other.x, other.y) { } }"); comp.VerifyDiagnostics( // (4,25): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C other) : this(other.x, other.y) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(4, 25) ); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_1() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_2() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : base() { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44782, "https://github.com/dotnet/roslyn/issues/44782")] public void RecordClone3() { var comp = CreateCompilation(@" using System; public record C(int x, int y) { public event Action E; public int Z; public int W = 123; }"); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 67 (0x43) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""System.Action C.E"" IL_0025: stfld ""System.Action C.E"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Z"" IL_0031: stfld ""int C.Z"" IL_0036: ldarg.0 IL_0037: ldarg.1 IL_0038: ldfld ""int C.W"" IL_003d: stfld ""int C.W"" IL_0042: ret } "); } [Fact] public void NominalRecordEquals() { var verifier = CompileAndVerify(@" using System; record C { private int X; private int Y { get; set; } private event Action E; public static void Main() { var c = new C { X = 1, Y = 2 }; c.E = () => { }; var c2 = new C { X = 1, Y = 2 }; c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics( // (5,17): warning CS0414: The field 'C.X' is assigned but its value is never used // private int X; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(5, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 101 (0x65) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0063 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0061 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0061 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C.X"" IL_0025: ldarg.1 IL_0026: ldfld ""int C.X"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: brfalse.s IL_0061 IL_0032: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0037: ldarg.0 IL_0038: ldfld ""int C.<Y>k__BackingField"" IL_003d: ldarg.1 IL_003e: ldfld ""int C.<Y>k__BackingField"" IL_0043: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0048: brfalse.s IL_0061 IL_004a: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004f: ldarg.0 IL_0050: ldfld ""System.Action C.E"" IL_0055: ldarg.1 IL_0056: ldfld ""System.Action C.E"" IL_005b: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_0060: ret IL_0061: ldc.i4.0 IL_0062: ret IL_0063: ldc.i4.1 IL_0064: ret }"); } [Fact] public void PositionalAndNominalSameEquals() { var v1 = CompileAndVerify(@" using System; record C(int X, string Y) { public event Action E; } ").VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var v2 = CompileAndVerify(@" using System; record C { public int X { get; } public string Y { get; } public event Action E; }").VerifyDiagnostics( // (7,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(7, 25) ); Assert.Equal(v1.VisualizeIL("C.Equals(C)"), v2.VisualizeIL("C.Equals(C)")); Assert.Equal(v1.VisualizeIL("C.Equals(object)"), v2.VisualizeIL("C.Equals(object)")); } [Fact] public void NominalRecordMembers() { var comp = CreateCompilation(@" #nullable enable record C { public int X { get; init; } public string Y { get; init; } }"); var members = comp.GlobalNamespace.GetTypeMember("C").GetMembers(); AssertEx.Equal(new[] { "System.Type! C.EqualityContract.get", "System.Type! C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X { get; init; }", "System.Int32 C.X.get", "void C.X.init", "System.String! C.<Y>k__BackingField", "System.String! C.Y { get; init; }", "System.String! C.Y.get", "void C.Y.init", "System.String! C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder! builder)", "System.Boolean C.operator !=(C? left, C? right)", "System.Boolean C.operator ==(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C! C." + WellKnownMemberNames.CloneMethodName + "()", "C.C(C! original)", "C.C()", }, members.Select(m => m.ToTestDisplayString(includeNonNullable: true))); } [Fact] public void PartialTypes_01() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X, int Y) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X, int Y) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X, int Y)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_02() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_03() { var src = @" partial record C { public int X = 1; } partial record C(int Y); partial record C { public int Z { get; } = 2; }"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stfld ""int C.X"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.2 IL_0010: stfld ""int C.<Z>k__BackingField"" IL_0015: ldarg.0 IL_0016: call ""object..ctor()"" IL_001b: ret }"); } [Fact] public void PartialTypes_04_PartialBeforeModifiers() { var src = @" partial public record C { } "; CreateCompilation(src).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record C Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void DataClassAndStruct() { var src = @" data class C1 { } data class C2(int X, int Y); data struct S1 { } data struct S2(int X, int Y);"; var comp = CreateCompilation(src, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (3,14): error CS8805: Program using top-level statements must be an executable. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int X, int Y);").WithLocation(3, 14), // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(2, 1), // (3,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(3, 1), // (3,14): error CS1514: { expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS1513: } expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS8803: Top-level statements must precede namespace and type declarations. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int X, int Y);").WithLocation(3, 14), // (3,14): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(3, 14), // (3,15): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(3, 15), // (3,15): error CS0165: Use of unassigned local variable 'X' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(3, 15), // (3,22): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(3, 22), // (3,22): error CS0165: Use of unassigned local variable 'Y' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(3, 22), // (4,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(4, 1), // (5,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(5, 1), // (5,15): error CS1514: { expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS1513: } expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(5, 15), // (5,16): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(5, 16), // (5,16): error CS0165: Use of unassigned local variable 'X' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(5, 16), // (5,20): error CS0128: A local variable or function named 'X' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "X").WithArguments("X").WithLocation(5, 20), // (5,23): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(5, 23), // (5,23): error CS0165: Use of unassigned local variable 'Y' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(5, 23), // (5,27): error CS0128: A local variable or function named 'Y' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Y").WithArguments("Y").WithLocation(5, 27) ); } [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] [Fact] public void ClassInheritingFromRecord() { var src = @" abstract record AbstractRecord {} class SomeClass : AbstractRecord {}"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,19): error CS8865: Only records may inherit from records. // class SomeClass : AbstractRecord {} Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "AbstractRecord").WithLocation(3, 19) ); } [Fact] public void RecordInheritance() { var src = @" class A { } record B : A { } record C : B { } class D : C { } interface E : C { } struct F : C { } enum G : C { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(3, 8), // (3,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record B : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (5,11): error CS8865: Only records may inherit from records. // class D : C { } Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "C").WithLocation(5, 11), // (6,15): error CS0527: Type 'C' in interface list is not an interface // interface E : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(6, 15), // (7,12): error CS0527: Type 'C' in interface list is not an interface // struct F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(7, 12), // (8,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum G : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(8, 10) ); } [Theory] [InlineData(true)] [InlineData(false)] public void RecordInheritance2(bool emitReference) { var src = @" public class A { } public record B { } public record C : B { }"; var comp = CreateCompilation(src); var src2 = @" record D : C { } record E : A { } interface F : C { } struct G : C { } enum H : C { } "; var comp2 = CreateCompilation(src2, parseOptions: TestOptions.Regular9, references: new[] { emitReference ? comp.EmitToImageReference() : comp.ToMetadataReference() }); comp2.VerifyDiagnostics( // (3,8): error CS0115: 'E.EqualityContract': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'E.Equals(A?)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.Equals(A?)").WithLocation(3, 8), // (3,8): error CS0115: 'E.PrintMembers(StringBuilder)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record E : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record E : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (4,15): error CS0527: Type 'C' in interface list is not an interface // interface F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(4, 15), // (5,12): error CS0527: Type 'C' in interface list is not an interface // struct G : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(5, 12), // (6,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum H : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(6, 10) ); } [Fact] public void GenericRecord() { var src = @" using System; record A<T> { public T Prop { get; init; } } record B : A<int>; record C<T>(T Prop2) : A<T>; class P { public static void Main() { var a = new A<int>() { Prop = 1 }; var a2 = a with { Prop = 2 }; Console.WriteLine(a.Prop + "" "" + a2.Prop); var b = new B() { Prop = 3 }; var b2 = b with { Prop = 4 }; Console.WriteLine(b.Prop + "" "" + b2.Prop); var c = new C<int>(5) { Prop = 6 }; var c2 = c with { Prop = 7, Prop2 = 8 }; Console.WriteLine(c.Prop + "" "" + c.Prop2); Console.WriteLine(c2.Prop2 + "" "" + c2.Prop); } }"; CompileAndVerify(src, expectedOutput: @" 1 2 3 4 6 5 8 7").VerifyDiagnostics(); } [Fact] public void RecordCloneSymbol() { var src = @" record R; record R2 : R"; var comp = CreateCompilation(src); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.False(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); } [Fact] public void AbstractRecordClone() { var src = @" abstract record R; abstract record R2 : R; record R3 : R2; abstract record R4 : R3; record R5 : R4; class C { public static void Main() { R r = new R3(); r = r with { }; R4 r4 = new R5(); r4 = r4 with { }; } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); Assert.Equal("R R." + WellKnownMemberNames.CloneMethodName + "()", clone.ToTestDisplayString()); Assert.True(clone.IsImplicitlyDeclared); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.True(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R2." + WellKnownMemberNames.CloneMethodName + "()", clone2.ToTestDisplayString()); Assert.True(clone2.IsImplicitlyDeclared); var r3 = comp.GlobalNamespace.GetTypeMember("R3"); var clone3 = (MethodSymbol)r3.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone3.IsOverride); Assert.False(clone3.IsVirtual); Assert.False(clone3.IsAbstract); Assert.Equal(0, clone3.ParameterCount); Assert.Equal(0, clone3.Arity); Assert.True(clone3.OverriddenMethod.Equals(clone2, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R3." + WellKnownMemberNames.CloneMethodName + "()", clone3.ToTestDisplayString()); Assert.True(clone3.IsImplicitlyDeclared); var r4 = comp.GlobalNamespace.GetTypeMember("R4"); var clone4 = (MethodSymbol)r4.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone4.IsOverride); Assert.False(clone4.IsVirtual); Assert.True(clone4.IsAbstract); Assert.Equal(0, clone4.ParameterCount); Assert.Equal(0, clone4.Arity); Assert.True(clone4.OverriddenMethod.Equals(clone3, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R4." + WellKnownMemberNames.CloneMethodName + "()", clone4.ToTestDisplayString()); Assert.True(clone4.IsImplicitlyDeclared); var r5 = comp.GlobalNamespace.GetTypeMember("R5"); var clone5 = (MethodSymbol)r5.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone5.IsOverride); Assert.False(clone5.IsVirtual); Assert.False(clone5.IsAbstract); Assert.Equal(0, clone5.ParameterCount); Assert.Equal(0, clone5.Arity); Assert.True(clone5.OverriddenMethod.Equals(clone4, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R5." + WellKnownMemberNames.CloneMethodName + "()", clone5.ToTestDisplayString()); Assert.True(clone5.IsImplicitlyDeclared); var verifier = CompileAndVerify(comp, expectedOutput: "", verify: Verification.Passes).VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: newobj ""R3..ctor()"" IL_0005: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000a: pop IL_000b: newobj ""R5..ctor()"" IL_0010: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: castclass ""R4"" IL_001a: pop IL_001b: ret }"); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithEventImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { event Action E1; } public record R1 : I1 { public event Action E1 { add { } remove { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithPropertyImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action P1 { get; set; } } public record R1 : I1 { public Action P1 { get; set; } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithMethodImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action M1(); } public record R1 : I1 { public Action M1() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void MergeInitializers_01() { var src = @" record C(int X) { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_02() { var src1 = @" partial record C(int X) { } "; var src2 = @" partial record C { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { X = 11, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_03() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { Y = 22, X = 11 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { Y = 22, X = 11 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_04() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { } "; var src3 = @" partial record C { public int Z = 33; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2 + src3, expectedOutput: "C { Y = 22, X = 11, Z = 33 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2, src3 }, expectedOutput: "C { Y = 22, X = 11, Z = 33 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_05() { var src1 = @" partial record C(int X) { public int U = 44; } "; var src2 = @" partial record C { public int Y = 22; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { X = 11, U = 44, Y = 22 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { X = 11, U = 44, Y = 22 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_06() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { public int U = 44; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2, expectedOutput: "C { Y = 22, X = 11, U = 44 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2 }, expectedOutput: "C { Y = 22, X = 11, U = 44 }").VerifyDiagnostics(); } [Fact] public void MergeInitializers_07() { var src1 = @" partial record C { public int Y = 22; } "; var src2 = @" partial record C(int X) { public int U = 44; } "; var src3 = @" partial record C { public int Z = 33; } class Test { static void Main() { System.Console.Write((new C(11)).ToString()); } } "; CompileAndVerify(src1 + src2 + src3, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics(); CompileAndVerify(new[] { src1, src2, src3 }, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics(); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/CSharp/Impl/CodeModel/ParameterFlagsExtensions.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; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal static class ParameterFlagsExtensions { public static ParameterFlags GetParameterFlags(this ParameterSyntax parameter) { ParameterFlags result = 0; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.RefKeyword: result |= ParameterFlags.Ref; break; case SyntaxKind.OutKeyword: result |= ParameterFlags.Out; break; case SyntaxKind.ParamsKeyword: result |= ParameterFlags.Params; break; } } return result; } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal static class ParameterFlagsExtensions { public static ParameterFlags GetParameterFlags(this ParameterSyntax parameter) { ParameterFlags result = 0; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.RefKeyword: result |= ParameterFlags.Ref; break; case SyntaxKind.OutKeyword: result |= ParameterFlags.Out; break; case SyntaxKind.ParamsKeyword: result |= ParameterFlags.Params; break; } } return result; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SymbolToProjectId.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.Runtime.CompilerServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <inheritdoc cref="Solution.GetOriginatingProjectId"/> public ProjectId? GetOriginatingProjectId(ISymbol? symbol) { if (symbol == null) return null; var projectId = GetOriginatingProjectIdWorker(symbol); // Validate some invariants we think should hold. We want to know if this breaks, which indicates some part // of our system not working as we might expect. If they break, create NFWs so we can find out and // investigate. if (SymbolKey.IsBodyLevelSymbol(symbol)) { // If this is a method-body-level symbol, then we will have it's syntax tree. Since we already have a // mapping from syntax-trees to docs, so we can immediately map this back to it's originating project. // // Note: we don't do this for all source symbols, only method-body-level ones. That's because other // source symbols may be *retargetted*. So you can have the same symbol retargetted into multiple // projects, but which have the same syntax-tree (which is only in one project). We need to actually // check it's assembly symbol so that we get the actual project it is from (the original project, or the // retargetted project). var syntaxTree = symbol.Locations[0].SourceTree; Contract.ThrowIfNull(syntaxTree); var documentId = this.GetDocumentState(syntaxTree, projectId: null)?.Id; if (documentId == null) { try { throw new InvalidOperationException( $"We should always be able to map a body symbol back to a document:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } else if (documentId.ProjectId != projectId) { try { throw new InvalidOperationException( $"Syntax tree for a body symbol should map to the same project as the body symbol's assembly:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}\r\n{documentId.ProjectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } } return projectId; } private ProjectId? GetOriginatingProjectIdWorker(ISymbol symbol) { LazyInitialization.EnsureInitialized(ref _unrootedSymbolToProjectId, s_createTable); // Walk up the symbol so we can get to the containing namespace/assembly that will be used to map // back to a project. while (symbol != null) { var result = GetProjectIdDirectly(symbol, _unrootedSymbolToProjectId); if (result != null) return result; symbol = symbol.ContainingSymbol; } return null; } private ProjectId? GetProjectIdDirectly( ISymbol symbol, ConditionalWeakTable<ISymbol, ProjectId?> unrootedSymbolToProjectId) { if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns)) { if (ns.ContainingCompilation != null) { // A namespace that spans a compilation. These don't belong to an assembly/module directly. // However, as we're looking for the project this corresponds to, we can look for the // source-module component (the first in the constituent namespaces) and then search using that. return GetOriginatingProjectId(ns.ConstituentNamespaces[0]); } } else if (symbol.IsKind(SymbolKind.Assembly) || symbol.IsKind(SymbolKind.NetModule) || symbol.IsKind(SymbolKind.DynamicType)) { if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId)) { // First, look through all the projects, and see if this symbol came from the primary assembly for // that project. (i.e. was a source symbol from that project, or was retargetted into that // project). If so, that's the originating project. // // If we don't find any primary results, then look through all the secondary assemblies (i.e. // references) for that project. This is the case for metadata symbols. A metadata symbol might be // found in many projects, so we just return the first result as that's just as good for finding the // metadata symbol as any other project. projectId = TryGetProjectId(symbol, primary: true) ?? TryGetProjectId(symbol, primary: false); // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two // threads tried to add the same item. #if !NETCOREAPP lock (unrootedSymbolToProjectId) { unrootedSymbolToProjectId.Remove(symbol); unrootedSymbolToProjectId.Add(symbol, projectId); } #else unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId); #endif } return projectId; } else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) && typeParameter.TypeParameterKind == TypeParameterKind.Cref) { // Cref type parameters don't belong to any containing symbol. But we can map them to a doc/project // using the declaring syntax of the type parameter itself. var tree = typeParameter.Locations[0].SourceTree; var doc = this.GetDocumentState(tree, projectId: null); return doc?.Id.ProjectId; } return null; ProjectId? TryGetProjectId(ISymbol symbol, bool primary) { foreach (var (id, tracker) in _projectIdToTrackerMap) { if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol, primary)) return id; } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <inheritdoc cref="Solution.GetOriginatingProjectId"/> public ProjectId? GetOriginatingProjectId(ISymbol? symbol) { if (symbol == null) return null; var projectId = GetOriginatingProjectIdWorker(symbol); // Validate some invariants we think should hold. We want to know if this breaks, which indicates some part // of our system not working as we might expect. If they break, create NFWs so we can find out and // investigate. if (SymbolKey.IsBodyLevelSymbol(symbol)) { // If this is a method-body-level symbol, then we will have it's syntax tree. Since we already have a // mapping from syntax-trees to docs, so we can immediately map this back to it's originating project. // // Note: we don't do this for all source symbols, only method-body-level ones. That's because other // source symbols may be *retargetted*. So you can have the same symbol retargetted into multiple // projects, but which have the same syntax-tree (which is only in one project). We need to actually // check it's assembly symbol so that we get the actual project it is from (the original project, or the // retargetted project). var syntaxTree = symbol.Locations[0].SourceTree; Contract.ThrowIfNull(syntaxTree); var documentId = this.GetDocumentState(syntaxTree, projectId: null)?.Id; if (documentId == null) { try { throw new InvalidOperationException( $"We should always be able to map a body symbol back to a document:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } else if (documentId.ProjectId != projectId) { try { throw new InvalidOperationException( $"Syntax tree for a body symbol should map to the same project as the body symbol's assembly:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}\r\n{documentId.ProjectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } } return projectId; } private ProjectId? GetOriginatingProjectIdWorker(ISymbol symbol) { LazyInitialization.EnsureInitialized(ref _unrootedSymbolToProjectId, s_createTable); // Walk up the symbol so we can get to the containing namespace/assembly that will be used to map // back to a project. while (symbol != null) { var result = GetProjectIdDirectly(symbol, _unrootedSymbolToProjectId); if (result != null) return result; symbol = symbol.ContainingSymbol; } return null; } private ProjectId? GetProjectIdDirectly( ISymbol symbol, ConditionalWeakTable<ISymbol, ProjectId?> unrootedSymbolToProjectId) { if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns)) { if (ns.ContainingCompilation != null) { // A namespace that spans a compilation. These don't belong to an assembly/module directly. // However, as we're looking for the project this corresponds to, we can look for the // source-module component (the first in the constituent namespaces) and then search using that. return GetOriginatingProjectId(ns.ConstituentNamespaces[0]); } } else if (symbol.IsKind(SymbolKind.Assembly) || symbol.IsKind(SymbolKind.NetModule) || symbol.IsKind(SymbolKind.DynamicType)) { if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId)) { // First, look through all the projects, and see if this symbol came from the primary assembly for // that project. (i.e. was a source symbol from that project, or was retargetted into that // project). If so, that's the originating project. // // If we don't find any primary results, then look through all the secondary assemblies (i.e. // references) for that project. This is the case for metadata symbols. A metadata symbol might be // found in many projects, so we just return the first result as that's just as good for finding the // metadata symbol as any other project. projectId = TryGetProjectId(symbol, primary: true) ?? TryGetProjectId(symbol, primary: false); // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two // threads tried to add the same item. #if !NETCOREAPP lock (unrootedSymbolToProjectId) { unrootedSymbolToProjectId.Remove(symbol); unrootedSymbolToProjectId.Add(symbol, projectId); } #else unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId); #endif } return projectId; } else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) && typeParameter.TypeParameterKind == TypeParameterKind.Cref) { // Cref type parameters don't belong to any containing symbol. But we can map them to a doc/project // using the declaring syntax of the type parameter itself. var tree = typeParameter.Locations[0].SourceTree; var doc = this.GetDocumentState(tree, projectId: null); return doc?.Id.ProjectId; } return null; ProjectId? TryGetProjectId(ISymbol symbol, bool primary) { foreach (var (id, tracker) in _projectIdToTrackerMap) { if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol, primary)) return id; } return null; } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpVarReducer.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.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpVarReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpVarReducer() : base(s_pool) { } public override bool IsApplicable(OptionSet optionSet) => optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value || optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Value || optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpVarReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpVarReducer() : base(s_pool) { } public override bool IsApplicable(OptionSet optionSet) => optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value || optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Value || optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value; } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/Implementation/Classification/SyntacticClassificationTaggerProvider.Tagger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal partial class SyntacticClassificationTaggerProvider { private class Tagger : ITagger<IClassificationTag>, IDisposable { private TagComputer? _tagComputer; public Tagger(TagComputer tagComputer) { _tagComputer = tagComputer; _tagComputer.TagsChanged += OnTagsChanged; } public event EventHandler<SnapshotSpanEventArgs>? TagsChanged; public IEnumerable<ITagSpan<IClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_tagComputer == null) throw new ObjectDisposedException(GetType().FullName); return _tagComputer.GetTags(spans); } private void OnTagsChanged(object? sender, SnapshotSpanEventArgs e) => TagsChanged?.Invoke(this, e); public void Dispose() { if (_tagComputer != null) { _tagComputer.TagsChanged -= OnTagsChanged; _tagComputer.DecrementReferenceCount(); _tagComputer = 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.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal partial class SyntacticClassificationTaggerProvider { private class Tagger : ITagger<IClassificationTag>, IDisposable { private TagComputer? _tagComputer; public Tagger(TagComputer tagComputer) { _tagComputer = tagComputer; _tagComputer.TagsChanged += OnTagsChanged; } public event EventHandler<SnapshotSpanEventArgs>? TagsChanged; public IEnumerable<ITagSpan<IClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_tagComputer == null) throw new ObjectDisposedException(GetType().FullName); return _tagComputer.GetTags(spans); } private void OnTagsChanged(object? sender, SnapshotSpanEventArgs e) => TagsChanged?.Invoke(this, e); public void Dispose() { if (_tagComputer != null) { _tagComputer.TagsChanged -= OnTagsChanged; _tagComputer.DecrementReferenceCount(); _tagComputer = null; } } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/CSharp/NavigationBar/CSharpEditorNavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigationBar; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.CSharp.NavigationBar { [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.CSharp), Shared] internal class CSharpEditorNavigationBarItemService : AbstractEditorNavigationBarItemService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEditorNavigationBarItemService(IThreadingContext threadingContext) : base(threadingContext) { } protected override async Task<bool> TryNavigateToItemAsync(Document document, WrappedNavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken) { await NavigateToSymbolItemAsync(document, item, (RoslynNavigationBarItem.SymbolItem)item.UnderlyingItem, textVersion, cancellationToken).ConfigureAwait(false); return 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigationBar; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.CSharp.NavigationBar { [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.CSharp), Shared] internal class CSharpEditorNavigationBarItemService : AbstractEditorNavigationBarItemService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEditorNavigationBarItemService(IThreadingContext threadingContext) : base(threadingContext) { } protected override async Task<bool> TryNavigateToItemAsync(Document document, WrappedNavigationBarItem item, ITextView textView, ITextVersion textVersion, CancellationToken cancellationToken) { await NavigateToSymbolItemAsync(document, item, (RoslynNavigationBarItem.SymbolItem)item.UnderlyingItem, textVersion, cancellationToken).ConfigureAwait(false); return true; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.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.Reflection Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' This class tests binding of various statements; i.e., the code in Binder_Statements.vb ' ' Tests should be added here for every construct that can be bound ' correctly, with a test that compiles, verifies, and runs code for that construct. ' Tests should also be added here for every diagnostic that can be generated. Public Class Binder_Statements_Tests Inherits BasicTestBase <Fact> Public Sub HelloWorld1() CompileAndVerify( <compilation name="HelloWorld1"> <file name="a.vb"> Module M Sub Main() System.Console.WriteLine("Hello, world!") End Sub End Module </file> </compilation>, expectedOutput:="Hello, world!") End Sub <Fact> Public Sub HelloWorld2() CompileAndVerify( <compilation name="HelloWorld2"> <file name="a.vb"> Imports System Module M1 Sub Main() dim x as object x = 42 Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x) End Sub End Module </file> </compilation>, expectedOutput:="Hello, world 135.2 42") End Sub <Fact> Public Sub LocalWithSimpleInitialization() CompileAndVerify( <compilation name="LocalWithSimpleInitialization"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim s As String = "Hello world" Console.WriteLine(s) s = nothing Console.WriteLine(s) Dim i As Integer = 1 Console.WriteLine(i) Dim d As Double = 1.5 Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello world 1 1.5 ]]>) End Sub <Fact> Public Sub LocalAsNew() CompileAndVerify( <compilation name="LocalAsNew"> <file name="a.vb"> Imports System Class C Sub New (msg as string) Me.msg = msg End Sub Sub Report() Console.WriteLine(msg) End Sub private msg as string End Class Module M1 Sub Main() dim myC as New C("hello") myC.Report() End Sub End Module </file> </compilation>, expectedOutput:="hello") End Sub <Fact> Public Sub LocalAsNewArrayError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalAsNewArrayError"> <file name="a.vb"> Imports System Class C Sub New() End Sub End Class Module M1 Sub Main() ' Arrays cannot be declared with 'New'. dim c1() as new C() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30053: Arrays cannot be declared with 'New'. dim c1() as new C() ~~~ </expected>) End Sub <Fact> Public Sub LocalAsNewArrayError001() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalAsNewArrayError"> <file name="a.vb"> Imports System Class X Dim a(), b As New S End Class Class X1 Dim a, b() As New S End Class Class X2 Dim a, b(3) As New S End Class Class X3 Dim a, b As New S(){} End Class Structure S End Structure Module M1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30053: Arrays cannot be declared with 'New'. Dim a(), b As New S ~~~ BC30053: Arrays cannot be declared with 'New'. Dim a, b() As New S ~~~ BC30053: Arrays cannot be declared with 'New'. Dim a, b(3) As New S ~~~~ BC30205: End of statement expected. Dim a, b As New S(){} ~ </expected>) End Sub <WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")> <Fact> Public Sub LocalSameNameAsOperatorAllowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalSameNameAsOperatorAllowed"> <file name="a.vb"> Imports System Class C Public Shared Operator IsTrue(ByVal w As C) As Boolean Dim IsTrue As Boolean = True Return IsTrue End Operator Public Shared Operator IsFalse(ByVal w As C) As Boolean Dim IsFalse As Boolean = True Return IsFalse End Operator End Class Module M1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub ParameterlessSub() CompileAndVerify( <compilation name="ParameterlessSub"> <file name="a.vb"> Imports System Module M1 Sub Goo() Console.WriteLine("Hello, world") Console.WriteLine() Console.WriteLine("Goodbye, world") End Sub Sub Main() Goo End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello, world Goodbye, world ]]>) End Sub <Fact> Public Sub CallStatement() CompileAndVerify( <compilation name="CallStatement"> <file name="a.vb"> Imports System Module M1 Sub Goo() Console.WriteLine("Call without parameters") End Sub Sub Goo(s as string) Console.WriteLine(s) End Sub Function SayHi as string return "Hi" End Function Function One as integer return 1 End Function Sub Main() Goo(SayHi) goo call goo call goo("call with parameters") dim i = One + One Console.WriteLine(i) i = One Console.WriteLine(i) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hi Call without parameters Call without parameters call with parameters 2 1 ]]>) End Sub <Fact> Public Sub CallStatementMethodNotFound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodNotFound"> <file name="a.vb"> Imports System Module M1 Sub Main() call goo End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'goo' is not declared. It may be inaccessible due to its protection level. call goo ~~~ </expected>) End Sub <WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")> <Fact> Public Sub CallStatementNothingAsInvocationExpression_Bug_4247() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Module M1 Sub Main() Dim myLocalArr as Integer() Dim myLocalVar as Integer = 42 call myLocalArr(0) call myLocalVar call Nothing call 911 call new Integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. call myLocalArr(0) ~~~~~~~~~~ BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime. call myLocalArr(0) ~~~~~~~~~~ BC30454: Expression is not a method. call myLocalVar ~~~~~~~~~~ BC30454: Expression is not a method. call Nothing ~~~~~~~ BC30454: Expression is not a method. call 911 ~~~ BC30454: Expression is not a method. call new Integer ~~~~~~~~~~~ </expected>) End Sub ' related to bug 4247 <Fact> Public Sub CallStatementNamespaceAsInvocationExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Namespace N1.N2 Module M1 Sub Main() call N1 call N1.N2 End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'N1' is a namespace and cannot be used as an expression. call N1 ~~ BC30112: 'N1.N2' is a namespace and cannot be used as an expression. call N1.N2 ~~~~~ </expected>) End Sub ' related to bug 4247 <WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")> <Fact> Public Sub CallStatementTypeAsInvocationExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Class Class1 End Class Module M1 Sub Main() call Class1 call Integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30109: 'Class1' is a class type and cannot be used as an expression. call Class1 ~~~~~~ BC30110: 'Integer' is a structure type and cannot be used as an expression. call Integer ~~~~~~~ </expected>) End Sub <Fact> Public Sub AssignmentStatement() CompileAndVerify( <compilation name="AssignmentStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim s As String s = "Hello world" Console.WriteLine(s) Dim i As Integer i = 1 Console.WriteLine(i) Dim d As Double d = 1.5 Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture)) d = i Console.WriteLine(d) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello world 1 1.5 1 ]]>) End Sub <Fact> Public Sub FieldAssignmentStatement() CompileAndVerify( <compilation name="FieldAssignmentStatement"> <file name="a.vb"> Imports System Class C1 public i as integer End class Structure S1 public s as string End Structure Module M1 Sub Main() dim myC as C1 = new C1 myC.i = 10 Console.WriteLine(myC.i) dim myS as S1 = new S1 myS.s = "a" Console.WriteLine(MyS.s) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 10 a ]]>) End Sub <Fact> Public Sub AssignmentWithBadLValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssignmentWithBadLValue"> <file name="a.vb"> Imports System Module M1 Function f as integer return 0 End function Sub s End Sub Sub Main() f = 0 s = 1 dim i as integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30068: Expression is a value and therefore cannot be the target of an assignment. f = 0 ~ BC30068: Expression is a value and therefore cannot be the target of an assignment. s = 1 ~ BC42024: Unused local variable: 'i'. dim i as integer ~ </expected>) End Sub <Fact> Public Sub MultilineIfStatement1() CompileAndVerify( <compilation name="MultilineIfStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim cond As Boolean Dim cond2 As Boolean Dim cond3 As Boolean cond = True cond2 = True cond3 = True If cond Then Console.WriteLine("1. ThenPart") End If If cond Then Console.WriteLine("2. ThenPart") Else Console.WriteLine("2. ElsePart") End If If cond Then Console.WriteLine("3. ThenPart") Else If cond2 Console.WriteLine("3. ElseIfPart") End If If cond Then Console.WriteLine("4. ThenPart") Else If cond2 Console.WriteLine("4. ElseIf1Part") Else If cond3 Console.WriteLine("4. ElseIf2Part") Else Console.WriteLine("4. ElsePart") End If cond = False If cond Then Console.WriteLine("5. ThenPart") End If If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart") End If If cond Then Console.WriteLine("7. ThenPart") Else If cond2 Console.WriteLine("7. ElseIfPart") End If If cond Then Console.WriteLine("8. ThenPart") Else If cond2 Console.WriteLine("8. ElseIf1Part") Else If cond3 Console.WriteLine("8. ElseIf2Part") Else Console.WriteLine("8. ElsePart") End If cond2 = false If cond Then Console.WriteLine("9. ThenPart") Else If cond2 Console.WriteLine("9. ElseIfPart") End If If cond Then Console.WriteLine("10. ThenPart") Else If cond2 Console.WriteLine("10. ElseIf1Part") Else If cond3 Console.WriteLine("10. ElseIf2Part") Else Console.WriteLine("10. ElsePart") End If cond3 = false If cond Then Console.WriteLine("11. ThenPart") Else If cond2 Console.WriteLine("11. ElseIf1Part") Else If cond3 Console.WriteLine("11. ElseIf2Part") Else Console.WriteLine("11. ElsePart") End If End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1. ThenPart 2. ThenPart 3. ThenPart 4. ThenPart 6. ElsePart 7. ElseIfPart 8. ElseIf1Part 10. ElseIf2Part 11. ElsePart ]]>) End Sub <Fact> Public Sub SingleLineIfStatement1() CompileAndVerify( <compilation name="SingleLineIfStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim cond As Boolean cond = True If cond Then Console.WriteLine("1. ThenPart") If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB") If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB") If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB") If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart") If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart") cond = false If cond Then Console.WriteLine("7. ThenPart") If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB") If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB") If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB") If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart") If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart") End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1. ThenPart 2. ThenPartA 2. ThenPartB 3. ThenPartA 3. ThenPartB 4. ThenPart 5. ThenPartA 5. ThenPartB 6. ThenPart 9. ElsePartA 9. ElsePartB 10. ElsePartA 10. ElsePartB 11. ElsePart 12. ElsePart ]]>) End Sub <Fact> Public Sub DoLoop1() CompileAndVerify( <compilation name="DoLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = true Do While breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = false Loop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop2() CompileAndVerify( <compilation name="DoLoop2"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false Do Until breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = true Loop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop3() CompileAndVerify( <compilation name="DoLoop3"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = true Do Console.WriteLine("Iterate {0}", x) breakLoop = false Loop While breakLoop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop4() CompileAndVerify( <compilation name="DoLoop4"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false Do Console.WriteLine("Iterate {0}", x) breakLoop = true Loop Until breakLoop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub WhileLoop1() CompileAndVerify( <compilation name="WhileLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false While not breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = true End While End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub ExitContinueDoLoop1() CompileAndVerify( <compilation name="ExitContinueDoLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() dim breakLoop as Boolean dim continueLoop as Boolean breakLoop = True: continueLoop = true Do While breakLoop Console.WriteLine("Stmt1") If continueLoop Then Console.WriteLine("Continuing") continueLoop = false Continue Do End If Console.WriteLine("Exiting") Exit Do Console.WriteLine("Stmt2") Loop Console.WriteLine("After Loop") End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Stmt1 Continuing Stmt1 Exiting After Loop ]]>) End Sub <Fact> Public Sub ExitSub() CompileAndVerify( <compilation name="ExitSub"> <file name="a.vb"> Imports System Module M1 Sub Main() dim breakLoop as Boolean breakLoop = True Do While breakLoop Console.WriteLine("Stmt1") Console.WriteLine("Exiting") Exit Sub Console.WriteLine("Stmt2") 'should not output Loop Console.WriteLine("After Loop") 'should not output End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Stmt1 Exiting ]]>) End Sub <Fact> Public Sub ExitFunction() CompileAndVerify( <compilation name="ExitFunction"> <file name="a.vb"> Imports System Module M1 Function Fact(i as integer) as integer fact = 1 do if i &lt;= 0 then exit function else fact = i * fact i = i - 1 end if loop End Function Sub Main() Console.WriteLine(Fact(0)) Console.WriteLine(Fact(3)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 6 ]]>) End Sub <Fact> Public Sub BadExit() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadExit"> <file name="a.vb"> Imports System Module M1 Sub Main() Do Exit Do ' ok Exit For Exit Try Exit Select Exit While Loop Exit Do ' outside loop End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ BC30099: 'Exit Select' can only appear inside a 'Select' statement. Exit Select ~~~~~~~~~~~ BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit Do ' outside loop ~~~~~~~ </expected>) End Sub <Fact> Public Sub BadContinue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadContinue"> <file name="a.vb"> Imports System Module M1 Sub Main() Do Continue Do ' ok Continue For Continue While Loop Continue Do ' outside loop End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30783: 'Continue For' can only appear inside a 'For' statement. Continue For ~~~~~~~~~~~~ BC30784: 'Continue While' can only appear inside a 'While' statement. Continue While ~~~~~~~~~~~~~~ BC30782: 'Continue Do' can only appear inside a 'Do' statement. Continue Do ' outside loop ~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Return1() CompileAndVerify( <compilation name="Return1"> <file name="a.vb"> Imports System Module M1 Function F1 as Integer F1 = 1 End Function Function F2 as Integer if true then F2 = 2 else return 3 end if End Function Function F3 as Integer return 3 End Function Sub S1 return End Sub Sub Main() dim result as integer result = F1() Console.WriteLine(result) result = F2() Console.WriteLine(result) result = F3() Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub <Fact> Public Sub BadReturn() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadReturn"> <file name="a.vb"> Imports System Module M1 Function F1 as Integer return End Function Sub S1 return 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30654: 'Return' statement in a Function, Get, or Operator must return a value. return ~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. return 1 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub NoReturnUnreachableEnd() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoReturnUnreachableEnd"> <file name="a.vb"> Imports System Module M1 Function goo() As Boolean While True End While End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub BadArrayInitWithExplicitArraySize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(3) as integer = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. dim a(3) as integer = 1 ~~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer()'. dim a(3) as integer = 1 ~ </expected>) End Sub <Fact> Public Sub BadArrayWithNegativeSize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayWithNegativeSize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(-3) as integer dim b = new integer(-3){} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. dim a(-3) as integer ~~ BC30611: Array dimensions cannot have a negative size. dim b = new integer(-3){} ~~ </expected>) End Sub <Fact> Public Sub ArrayWithMinusOneUpperBound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayWithNegativeSize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(-1) as integer dim b = new integer(-1){} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")> <Fact()> Public Sub MultiDimensionalArrayWithTooFewInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiDimensionalArrayWithTooFewInitializers"> <file name="Program.vb"> Module Program Sub Main() Dim x = New Integer(0, 1) {{}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30567: Array initializer is missing 2 elements. Dim x = New Integer(0, 1) {{}} ~~ </expected>) End Sub <WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")> <Fact()> Public Sub Max32ArrayDimensionsAreAllowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Max32ArrayDimensionsAreAllowed"> <file name="Program.vb"> Module Program Sub Main() Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {} Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {} Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {} Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {} End Sub End Module </file> </compilation>). VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"), Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"), Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)")) End Sub <Fact> Public Sub GotoIf() CompileAndVerify( <compilation name="GotoIf"> <file name="a.vb"> Imports System Module M1 Sub GotoIf() GoTo l1 If False Then l1: Console.WriteLine("Jump into If") End If End Sub Sub GotoWhile() GoTo l1 While False l1: Console.WriteLine("Jump into While") End While End Sub Sub GotoDo() GoTo l1 Do While False l1: Console.WriteLine("Jump into Do") Loop End Sub Sub GotoSelect() Dim i As Integer = 0 GoTo l1 Select Case i Case 0 l1: Console.WriteLine("Jump into Select") End Select End Sub Sub Main() GotoIf() GotoWhile() GotoDo() GotoSelect() End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Jump into If Jump into While Jump into Do Jump into Select ]]>) End Sub <Fact()> Public Sub GotoIntoBlockErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoBlockErrors"> <file name="a.vb"> Imports System Module M1 Sub GotoFor() For i as Integer = 0 To 10 l1: Console.WriteLine() Next GoTo l1 End Sub Sub GotoWith() Dim c1 = New C() With c1 l1: Console.WriteLine() End With GoTo l1 End Sub Sub GotoUsing() Using c1 as IDisposable = nothing l1: Console.WriteLine() End Using GoTo l1 End Sub Sub GotoTry() Try l1: Console.WriteLine() Finally End Try GoTo l1 End Sub Sub GotoLambda() Dim x = Sub() l1: End Sub GoTo l1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo l1 ~~ BC30002: Type 'C' is not defined. Dim c1 = New C() ~ BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement. GoTo l1 ~~ BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement. GoTo l1 ~~ BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo l1 ~~ BC30132: Label 'l1' is not defined. GoTo l1 ~~ </expected>) End Sub <Fact()> Public Sub GotoDecimalLabels() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoDecimalLabels"> <file name="a.vb"> Imports System Module M Sub Main() 1 : Goto &amp;H2 2 : Goto 01 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")> <Fact()> Public Sub GotoUndefinedLabel() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoUndefinedLabel"> <file name="a.vb"> Imports System Class c1 Shared Sub Main() GoTo lab1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30132: Label 'lab1' is not defined. GoTo lab1 ~~~~ </expected>) End Sub <WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")> <Fact()> Public Sub ArrayModifiersOnVariableAndType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayModifiersOnVariableAndType"> <file name="a.vb"> Imports System Module M1 public a() as integer() public b(1) as integer() Sub S1 dim a() as integer() = nothing dim b(1) as string() End Sub Sub S2(x() as integer()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31087: Array modifiers cannot be specified on both a variable and its type. public a() as integer() ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. public b(1) as integer() ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. dim a() as integer() = nothing ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. dim b(1) as string() ~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. Sub S2(x() as integer()) ~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Bug6663() ' Test dependent on referenced mscorlib, but NOT system.dll. Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="Bug6663"> <file name="a.vb"> Imports System Module Program Sub Main() Console.WriteLine("".ToString() = "".ToString()) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:="True") End Sub <WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")> <Fact()> Public Sub Bug6637() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Option Infer Off Imports System Module M1 Sub Main() Dim a(3) As Integer For i = 0 To 3 Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'i' is not declared. It may be inaccessible due to its protection level. For i = 0 To 3 ~ </expected>) End Sub <WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")> <Fact()> Public Sub Bug6662() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Option Infer Off Class C Shared Sub M() For i = Nothing To 10 Dim d as System.Action = Sub() i = i + 1 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'i' is not declared. It may be inaccessible due to its protection level. For i = Nothing To 10 ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Dim d as System.Action = Sub() i = i + 1 ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Dim d as System.Action = Sub() i = i + 1 ~ </expected>) End Sub <WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")> <Fact()> Public Sub ExtTryFromFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Try End Try Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {SystemCoreRef}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchNotLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotLocal"> <file name="goo.vb"> Module M1 Private ex as System.Exception Sub Main() Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")> Public Sub Bug651622() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="goo.vb"> Module Module1 Sub Main() Try Catch Main Catch x as System.Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch Main ~~~~ </expected>) End Sub <Fact()> Public Sub CatchStatic() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchStatic"> <file name="goo.vb"> Imports System Module M1 Sub Main() Static ex as exception = nothing Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <Fact()> Public Sub CatchUndeclared() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchUndeclared"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Main() Try ' Explicit off does not have effect on Catch - ex is still undefined. Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'ex' is not declared. It may be inaccessible due to its protection level. Catch ex ~~ </expected>) End Sub <Fact()> Public Sub CatchNotException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Main() Dim ex as String = "qq" Try Catch ex End Try Try Catch ex1 as String End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch ex ~~ BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch ex1 as String ~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchNotVariableOrParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotVariableOrParameter"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Goo End Sub Sub Main() Try Catch Goo End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch Goo ~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try Catch ex Catch ex1 as Exception Catch End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ~~~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try Catch Catch ex Catch ex1 as Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex ~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try ' the following is NOT considered as catching all System.Exceptions Catch When true Catch ex ' filter does NOT make this reachable. Catch ex1 as Exception When true ' implicitly this is a "Catch ex As Exception When true" so still unreachable Catch When true Catch ex1 as Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception When true ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch When true ~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchOverlapped() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex As SystemException = Nothing Try ' the following is NOT considered as catching all System.Exceptions Catch When True Catch ex ' filter does NOT make this reachable. Catch ex1 As ArgumentException When True ' implicitly this is a "Catch ex As Exception When true" Catch When True ' this is ok since it is not derived from SystemException ' and catch above has a filter Catch ex1 As ApplicationException End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'. Catch ex1 As ArgumentException When True ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Dim field As String Function Goo(Of T)(ex As Exception) As Exception Dim ex1 As SystemException = Nothing Try Dim ex2 As Exception = nothing Catch ex As Exception Catch ex1 As Exception Catch Goo As ArgumentException When True ' this is ok Catch ex2 As exception Dim ex3 As exception = nothing 'this is ok Catch ex3 As ApplicationException ' this is ok Catch field As Exception End Try return nothing End Function Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'ex' is already declared as a parameter of this method. Catch ex As Exception ~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 As Exception ~~~~~~~~~~~~~~~~~~~~~~ BC30616: Variable 'ex1' hides a variable in an enclosing block. Catch ex1 As Exception ~~~ BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'. Catch Goo As ArgumentException When True ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30290: Local variable cannot have the same name as the function containing it. Catch Goo As ArgumentException When True ~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex2 As exception ~~~~~~~~~~~~~~~~~~~~~~ BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'. Catch ex3 As ApplicationException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch field As Exception ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")> <Fact()> Public Sub CatchShadowingGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Class cls3(Of T As NullReferenceException) Sub scen3() Try Catch ex As T Catch ex As NullReferenceException End Try End Sub Sub scen4() Try Catch ex As NullReferenceException 'COMPILEWarning: BC42029 ,"Catch ex As T" Catch ex As T End Try End Sub End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'. Catch ex As T ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub GotoOutOfFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoOutOfFinally"> <file name="goo.vb"> Imports System Module M1 Sub Main() l1: Try Finally try goto l1 catch End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. goto l1 ~~ </expected>) End Sub <Fact()> Public Sub BranchOutOfFinally1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BranchOutOfFinally1"> <file name="goo.vb"> Imports System Module M1 Sub Main() for i as integer = 1 to 10 Try Finally continue for End Try Next End Sub Function Goo() as integer l1: Try Finally try return 1 catch return 1 End Try End Try End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. continue for ~~~~~~~~~~~~ BC30101: Branching out of a 'Finally' is not valid. return 1 ~~~~~~~~ BC30101: Branching out of a 'Finally' is not valid. return 1 ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub GotoFromCatchToTry() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoFromCatchToTry"> <file name="goo.vb"> Imports System Module M1 Sub Main() Try Catch ex As Exception l1: Try GoTo l1 Catch ex2 As Exception GoTo l1 Finally End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub GotoFromCatchToTry1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoFromCatchToTry"> <file name="goo.vb"> Imports System Module M1 Sub Main() Try l1: Catch ex As Exception Try GoTo l1 Catch ex2 As Exception GoTo l1 Finally End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub UnassignedVariableInLateAddressOf() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter"> <file name="goo.vb"> Option Strict Off Imports System Module Program Delegate Sub d1(ByRef x As Integer, y As Integer) Sub Main() Dim obj As Object '= New cls1 Dim o As d1 = AddressOf obj.goo Dim l As Integer = 0 o(l, 2) Console.WriteLine(l) End Sub Class cls1 Shared Sub goo(ByRef x As Integer, y As Integer) x = 42 Console.WriteLine(x + y) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Dim o As d1 = AddressOf obj.goo ~~~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Dim B as StackOverflowException Dim C as Exception Try A = new ApplicationException B = new StackOverflowException C = new Exception Console.Writeline(A) 'this is ok Catch ex as NullReferenceException When A.Message isnot nothing Catch ex as DivideByZeroException Console.Writeline(B) Finally Console.Writeline(C) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Catch ex as NullReferenceException When A.Message isnot nothing ~ BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(B) ~ BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(C) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter1"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try ' ok , A is assigned in the filter and in the catch Catch A When A.Message isnot nothing Console.Writeline(A) Catch ex as Exception A = new ApplicationException Finally 'error Console.Writeline(A) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter2"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch End Try Console.Writeline(A) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter3"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch try Finally A = new ApplicationException End Try End Try Console.Writeline(A) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter4"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch try Finally A = new ApplicationException End Try Finally Console.Writeline(A) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub ThrowNotValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly Property Moo As Exception Get Return New Exception End Get End Property WriteOnly Property Boo As Exception Set(value As Exception) End Set End Property Sub Main() Throw Moo Throw Boo End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'Boo' is 'WriteOnly'. Throw Boo ~~~ </expected>) End Sub <Fact()> Public Sub ThrowNotException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly e as new Exception ReadOnly s as string = "qq" Sub Main() Throw e Throw s End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw s ~~~~~~~ </expected>) End Sub <Fact()> Public Sub RethrowNotInCatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RethrowNotInCatch"> <file name="goo.vb"> Imports System Module M1 Sub Main() Throw Try Throw Catch ex As Exception Throw Dim a As Action = Sub() ex.ToString() Throw End Sub Try Throw Catch Throw Finally Throw End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ </expected>) End Sub <Fact()> Public Sub ForNotValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Moo = 1 to Moo step Moo ~~~ BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Boo = 1 to Boo step Boo ~~~ BC30524: Property 'Boo' is 'WriteOnly'. For Boo = 1 to Boo step Boo ~~~ BC30524: Property 'Boo' is 'WriteOnly'. For Boo = 1 to Boo step Boo ~~~ </expected>) End Sub <Fact()> Public Sub CustomDatatypeForLoop() Dim source = <compilation> <file name="goo.vb"><![CDATA[ Imports System Module Module1 Public Sub Main() Dim x As New c1 For x = 1 To 3 Console.WriteLine("hi") Next End Sub End Module Public Class c1 Public val As Integer Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1 Console.WriteLine("c1::CType(Integer) As c1") Dim c As New c1 c.val = arg1 'what happens if this is last statement? Return c End Operator Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer Console.WriteLine("c1::CType(c1) As Integer") Dim x As Integer x = arg1.val Return x End Operator Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1 Console.WriteLine("c1::+(c1, c1) As c1") Dim c As New c1 c.val = arg1.val + arg2.val Return c End Operator Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1 Console.WriteLine("c1::-(c1, c1) As c1") Dim c As New c1 c.val = arg1.val - arg2.val Return c End Operator Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean Console.WriteLine("c1::>=(c1, Integer) As Boolean") If arg1.val >= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean Console.WriteLine("c1::<=(c1, Integer) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean Console.WriteLine("c1::<=(Integer, c1) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean Console.WriteLine("c1::>=(Integer, c1) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean Console.WriteLine("c1::<=(c1, c1) As Boolean") If arg1.val <= arg2.val Then Return True Else Return False End If End Operator Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean Console.WriteLine("c1::>=(c1, c1) As Boolean") If arg1.val >= arg2.val Then Return True Else Return False End If End Operator End Class ]]> </file> </compilation> CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1 c1::CType(Integer) As c1 c1::CType(Integer) As c1 c1::-(c1, c1) As c1 c1::>=(c1, c1) As Boolean c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean ]]>) End Sub <Fact()> Public Sub SelectCase1_SwitchTable() CompileAndVerify( <compilation name="SelectCase1"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) Select Case number Case 0 Console.WriteLine("Equal to 0") Case 1, 2, 3, 4, 5 Console.WriteLine("Between 1 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9, 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[0:Equal to 0 1:Between 1 and 5, inclusive 2:Between 1 and 5, inclusive 3:Between 1 and 5, inclusive 4:Between 1 and 5, inclusive 5:Between 1 and 5, inclusive 6:Between 6 and 8, inclusive 7:Between 6 and 8, inclusive 8:Between 6 and 8, inclusive 9:Equal to 9 or 10 10:Equal to 9 or 10 11:Greater than 10]]>) End Sub <Fact()> Public Sub SelectCase2_IfList() CompileAndVerify( <compilation name="SelectCase2"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) Select Case number Case Is < 1 Console.WriteLine("Less than 1") Case 1 To 5 Console.WriteLine("Between 1 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[0:Less than 1 1:Between 1 and 5, inclusive 2:Between 1 and 5, inclusive 3:Between 1 and 5, inclusive 4:Between 1 and 5, inclusive 5:Between 1 and 5, inclusive 6:Between 6 and 8, inclusive 7:Between 6 and 8, inclusive 8:Between 6 and 8, inclusive 9:Equal to 9 or 10 10:Equal to 9 or 10 11:Greater than 10]]>) End Sub <WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")> <Fact()> Public Sub ImplicitVarInRedim() CompileAndVerify( <compilation name="HelloWorld1"> <file name="a.vb"> Option Explicit Off Module M Sub Main() Redim x(10) System.Console.WriteLine("OK") End Sub End Module </file> </compilation>, expectedOutput:="OK") End Sub <Fact()> Public Sub EndStatementsInMethodBodyShouldNotThrowNYI() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EndStatementsInMethodBodyShouldNotThrowNYI"> <file name="a.vb"> Namespace N1 Public Class C1 Public Sub S1() for i as integer = 23 to 42 next next do loop while true loop end if end select end try end using end while end with end synclock Try Catch ex As System.Exception End Try catch Try Catch ex As System.Exception finally finally End Try finally End Sub Public Sub S2 end namespace end module end class end structure end interface end enum end function end operator end property end get end set end event end addhandler end removehandler end raiseevent End Sub end Class end Namespace Namespace N2 Class C2 function F1() as integer end sub return 42 end function End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30481: 'Class' statement must end with a matching 'End Class'. Public Class C1 ~~~~~~~~~~~~~~~ BC30092: 'Next' must be preceded by a matching 'For'. next ~~~~ BC30091: 'Loop' must be preceded by a matching 'Do'. loop ~~~~ BC30087: 'End If' must be preceded by a matching 'If'. end if ~~~~~~ BC30088: 'End Select' must be preceded by a matching 'Select Case'. end select ~~~~~~~~~~ BC30383: 'End Try' must be preceded by a matching 'Try'. end try ~~~~~~~ BC36007: 'End Using' must be preceded by a matching 'Using'. end using ~~~~~~~~~ BC30090: 'End While' must be preceded by a matching 'While'. end while ~~~~~~~~~ BC30093: 'End With' must be preceded by a matching 'With'. end with ~~~~~~~~ BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'. end synclock ~~~~~~~~~~~~ BC30380: 'Catch' cannot appear outside a 'Try' statement. catch ~~~~~ BC30381: 'Finally' can only appear once in a 'Try' statement. finally ~~~~~~~ BC30382: 'Finally' cannot appear outside a 'Try' statement. finally ~~~~~~~ BC30026: 'End Sub' expected. Public Sub S2 ~~~~~~~~~~~~~ BC30622: 'End Module' must be preceded by a matching 'Module'. end module ~~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. end class ~~~~~~~~~ BC30621: 'End Structure' must be preceded by a matching 'Structure'. end structure ~~~~~~~~~~~~~ BC30252: 'End Interface' must be preceded by a matching 'Interface'. end interface ~~~~~~~~~~~~~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. end enum ~~~~~~~~ BC30430: 'End Function' must be preceded by a matching 'Function'. end function ~~~~~~~~~~~~ BC33007: 'End Operator' must be preceded by a matching 'Operator'. end operator ~~~~~~~~~~~~ BC30431: 'End Property' must be preceded by a matching 'Property'. end property ~~~~~~~~~~~~ BC30630: 'End Get' must be preceded by a matching 'Get'. end get ~~~~~~~ BC30632: 'End Set' must be preceded by a matching 'Set'. end set ~~~~~~~ BC31123: 'End Event' must be preceded by a matching 'Custom Event'. end event ~~~~~~~~~ BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration. end addhandler ~~~~~~~~~~~~~~ BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration. end removehandler ~~~~~~~~~~~~~~~~~ BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration. end raiseevent ~~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End Sub ~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. end Class ~~~~~~~~~ BC30623: 'End Namespace' must be preceded by a matching 'Namespace'. end Namespace ~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. end sub ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub AddHandlerMissingStuff() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") AddHandler v.DomainUnload, AddHandler , del AddHandler End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30201: Expression expected. AddHandler v.DomainUnload, ~ BC30201: Expression expected. AddHandler , del ~ BC30196: Comma expected. AddHandler ~ BC30201: Expression expected. AddHandler ~ BC30201: Expression expected. AddHandler ~ </expected>) End Sub <Fact()> Public Sub AddHandlerUninitialized() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() ' no warnings here, variable is used Dim del As System.EventHandler ' warning here Dim v = AppDomain.CreateDomain("qq") AddHandler v.DomainUnload, del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime. AddHandler v.DomainUnload, del ~~~ </expected>) End Sub <Fact()> Public Sub AddHandlerNotSimple() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") ' real event with arg list AddHandler (v.DomainUnload()), del ' not an event AddHandler (v.GetType()), del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name. AddHandler (v.DomainUnload()), del ~~~~~~~~~~~~~~~~ BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name. AddHandler (v.GetType()), del ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub RemoveHandlerLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module MyClass1 Sub Main(args As String()) Dim v = AppDomain.CreateDomain("qq") RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload") AppDomain.Unload(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event. RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub RemoveHandlerNotEvent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") ' not an event AddHandler (v.GetType), del ' not anything AddHandler v.GetTyp, del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'GetType' is not an event of 'AppDomain'. AddHandler (v.GetType), del ~~~~~~~ BC30456: 'GetTyp' is not a member of 'AppDomain'. AddHandler v.GetTyp, del ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AddHandlerNoConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim v = AppDomain.CreateDomain("qq") AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload") AddHandler v.DomainUnload, AddressOf H Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload") AddHandler v.DomainUnload, del End Sub Sub H(i as integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'. AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'. AddHandler v.DomainUnload, AddressOf H ~ BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'. AddHandler v.DomainUnload, del ~~~ </expected>) End Sub <Fact()> Public Sub LegalGotoCasesTryCatchFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LegalGotoCasesTryCatchFinally"> <file name="a.vb"> Module M1 Sub Main() dim x1 = function() labelOK6: goto labelok7 if true then goto labelok6 labelok7: end if return 23 end function dim x2 = sub() labelOK8: goto labelok9 if true then goto labelok8 labelok9: end if end sub Try Goto LabelOK1 LabelOK1: Catch Goto LabelOK2 LabelOK2: Try goto LabelOK1 goto LabelOK2: LabelOK5: Catch goto LabelOK1 goto LabelOK5 goto LabelOK2 Finally End Try Finally Goto LabelOK3 LabelOK3: End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")> <Fact()> Public Sub Bug10583() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LegalGotoCasesTryCatchFinally"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Try GoTo label GoTo label5 Catch ex As Exception label: Finally label5: End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label ~~~~~ BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label5 ~~~~~~ </expected>) End Sub <WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")> <Fact()> Public Sub SelectCase_ImplicitOperator() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase"> <file name="a.vb"><![CDATA[ Imports System Module M1 Class X Public Shared Operator =(left As X, right As X) As Boolean Return True End Operator Public Shared Operator <>(left As X, right As X) As Boolean Return True End Operator Public Shared Widening Operator CType(expandedName As String) As X Return New X() End Operator End Class Sub Main() End Sub Sub Test(x As X) Select Case x Case "a" Console.WriteLine("Equal to a") Case "s" Console.WriteLine("Equal to A") Case "3" Console.WriteLine("Error") Case "5" Console.WriteLine("Error") Case "6" Console.WriteLine("Error") Case "9" Console.WriteLine("Error") Case "11" Console.WriteLine("Error") Case "12" Console.WriteLine("Error") Case "13" Console.WriteLine("Error") Case Else Console.WriteLine("Error") End Select End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> </expected>) End Sub <WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")> <Fact()> Public Sub Binding_Return_As_Declaration() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="SelectCase"> <file name="a.vb"><![CDATA[ Class Program Shared Main() Return Nothing End sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30689: Statement cannot appear outside of a method body. Return Nothing ~~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End sub ~~~~~~~ </expected>) End Sub <WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")> <Fact> Public Sub WhileOutOfMethod() Dim source = <compilation> <file name="a.vb"> While (true) </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)")) End Sub <WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")> <Fact> Public Sub WhileOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 While (true) End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)")) End Sub <WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")> <Fact> Public Sub IfOutOfMethod() Dim source = <compilation> <file name="a.vb"> If (true) </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)")) End Sub <WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")> <Fact> Public Sub IfOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 If (true) End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)")) End Sub <WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")> <Fact> Public Sub TryOutOfMethod() Dim source = <compilation> <file name="a.vb"> Try Catch </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch")) End Sub <WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")> <Fact> Public Sub TryOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Try Catch End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch")) End Sub <WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")> <Fact> Public Sub DoOutOfMethod() Dim source = <compilation> <file name="a.vb"> Do </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do")) End Sub <WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")> <Fact> Public Sub DoOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Do End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do")) End Sub <WorkItem(11031, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseOutOfMethod() Dim source = <compilation> <file name="a.vb"> Else </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else")) End Sub <WorkItem(11031, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Else End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else")) End Sub <WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")> <Fact()> Public Sub DuplicateNullableLocals() Dim source = <compilation> <file name="a.vb"> Option Explicit Off Module M Sub S() Dim A? As Integer = 1 Dim A? As Integer? = 1 End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"), Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A")) End Sub <WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")> <Fact()> Public Sub IllegalModifiers() Dim source = <compilation> <file name="a.vb"> Class C Public Custom E End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom")) End Sub <Fact()> Public Sub InvalidCode_ConstInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Const Interface </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC30397: 'Const' is not valid on an Interface declaration. Const Interface ~~~~~ BC30253: 'Interface' must end with a matching 'End Interface'. Const Interface ~~~~~~~~~~~~~~~ BC30203: Identifier expected. Const Interface ~ </errors>) End Sub <WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")> <Fact()> Public Sub InvalidCode_Event() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Event </file> </compilation>) compilation.AssertTheseParseDiagnostics(<errors> BC30203: Identifier expected. Event ~ </errors>) End Sub <Fact> Public Sub StopAndEnd_1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Public Sub Main() Dim m = GetType(Module1) System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags) System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags) System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags) Try System.Console.WriteLine("Before End") TestEnd() System.Console.WriteLine("After End") Finally System.Console.WriteLine("In Finally") End Try System.Console.WriteLine("After Try") End Sub Sub TestEnd() End End Sub Sub TestStop() Stop End Sub Sub Dummy() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, symbolValidator:=Sub(m As ModuleSymbol) Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization, DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes) Assert.Equal(MethodImplAttributes.Managed, DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes) Assert.Equal(MethodImplAttributes.Managed, DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes) End Sub) compilationVerifier.VerifyIL("Module1.TestEnd", <![CDATA[ { // Code size 6 (0x6) .maxstack 0 IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()" IL_0005: ret } ]]>) compilationVerifier.VerifyIL("Module1.TestStop", <![CDATA[ { // Code size 6 (0x6) .maxstack 0 IL_0000: call "Sub System.Diagnostics.Debugger.Break()" IL_0005: ret } ]]>) compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)) AssertTheseDiagnostics(compilation, <expected> BC30615: 'End' statement cannot be used in class library projects. End ~~~ </expected>) End Sub <Fact> Public Sub StopAndEnd_2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Public Sub Main() Dim x As Object Dim y As Object Stop x.ToString() End y.ToString() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.ToString() ~ </expected>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub StopAndEnd_3() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public state As Integer = 0 Public Sub Main() On Error GoTo handler Throw New NullReferenceException() Stop Console.WriteLine("Done") Return handler: Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType()) If state = 1 Then Resume End If Resume Next End Sub End Module Namespace System.Diagnostics Public Class Debugger Public Shared Sub Break() Console.WriteLine("In Break") Select Case Module1.state Case 0, 1 Module1.state += 1 Case Else Console.WriteLine("Test issue!!!") Return End Select Throw New NotSupportedException() End Sub End Class End Namespace ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:= <![CDATA[ System.NullReferenceException In Break System.NotSupportedException In Break System.NotSupportedException Done ]]>) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithSingleLineIf() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithSingleLineIfWithDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC30615: 'End' statement cannot be used in class library projects. If True Then End Else Console.WriteLine("Test") ~~~ </expected>) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithMultiLineIf() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End If End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation) End Sub <WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")> <Fact> Public Sub Regress660010() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class C Inherits value End C ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences) AssertTheseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class C ~~~~~~~ BC30002: Type 'value' is not defined. Inherits value ~~~~~ BC30678: 'End' statement not valid. End C ~~~ </expected>) End Sub <WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")> <Fact> Public Sub NotYetImplementedStatement() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class C Sub M() Inherits A Implements I Imports X Option Strict On End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) AssertTheseDiagnostics(compilation, <expected> BC30024: Statement is not valid inside a method. Inherits A ~~~~~~~~~~ BC30024: Statement is not valid inside a method. Implements I ~~~~~~~~~~~~ BC30024: Statement is not valid inside a method. Imports X ~~~~~~~~~ BC30024: Statement is not valid inside a method. Option Strict On ~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InaccessibleRemoveAccessor() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action TestEvent .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::add_Test .method family specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module Class E2 Inherits E1 Sub Main() Dim d As System.Action = Nothing AddHandler Test, d RemoveHandler Test, d End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InaccessibleAddAccessor() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action TestEvent .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method family specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module Class E2 Inherits E1 Sub Main() Dim d As System.Action = Nothing AddHandler Test, d RemoveHandler Test, d End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'. AddHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub EventTypeIsNotADelegate() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class E1 obj) cil managed synchronized { IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class E1 obj) cil managed synchronized { IL_0017: ret } // end of method E1::remove_Test .event E1 Test { .addon instance void E1::add_Test(class E1) .removeon instance void E1::remove_Test(class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC37223: 'Public Event Test As E1' is an unsupported event. AddHandler e.Test, e ~~~~~~ BC37223: 'Public Event Test As E1' is an unsupported event. RemoveHandler e.Test, e ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_01() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class E1 obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class E1) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_02() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test() cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test() .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_03() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action, class E1) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_01() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class E1 obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_02() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test() cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test() } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_03() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj1) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub NonVoidAccessors() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance int32 add_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0016: ldc.i4.0 IL_0017: ret } // end of method E1::add_Test .method public specialname instance int32 remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0016: ldc.i4.0 IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance int32 E1::add_Test(class [mscorlib]System.Action) .removeon instance int32 E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation1, expectedOutput:="add_Test remove_Test") End Sub ''' <summary> ''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name, ''' but is instead parsed as a statement separator when it immediately follows an XML name. ''' If the next token is an identifier or keyword, it should be parsed as a separate statement. ''' An XML name should never include more than one colon. ''' See also: http://fileformat.info/info/unicode/char/FF1A ''' </summary> <Fact> <WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")> Public Sub FullWidthColonInXmlNames() ' FULLWIDTH COLON is represented by "~" below Dim source = <![CDATA[ Imports System Module M Sub Main() Test1() Test2() Test3() Test4() Test5() Test6() Test7() Test8() End Sub Sub Test1() Console.WriteLine(">1") Dim x = <a/>.@xml:goo Console.WriteLine("<1") End Sub Sub Test2() Console.WriteLine(">2") Dim x = <a/>.@xml:goo:goo Console.WriteLine("<2") End Sub Sub Test3() Console.WriteLine(">3") Dim x = <a/>.@xml:return Console.WriteLine("<3") End Sub Sub Test4() Console.WriteLine(">4") Dim x = <a/>.@xml:return:return Console.WriteLine("<4") End Sub Sub Test5() Console.WriteLine(">5") Dim x = <a/>.@xml~goo Console.WriteLine("<5") End Sub Sub Test6() Console.WriteLine(">6") Dim x = <a/>.@xml~return Console.WriteLine("<6") End Sub Sub Test7() Console.WriteLine(">7") Dim x = <a/>.@xml~goo~return Console.WriteLine("<7") End Sub Sub Test8() Console.WriteLine(">8") Dim x = <a/>.@xml~REM Console.WriteLine("<8") End Sub Sub goo Console.WriteLine("goo") End Sub Sub [return] Console.WriteLine("return") End Sub Sub [REM] Console.WriteLine("REM") End Sub End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="FullWidthColonInXmlNames"> <file name="M.vb"><%= source %></file> </compilation>, XmlReferences, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[ >1 <1 >2 goo <2 >3 <3 >4 >5 goo <5 >6 >7 goo >8 <8]]>.Value.Replace(vbLf, Environment.NewLine)) 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.Reflection Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' This class tests binding of various statements; i.e., the code in Binder_Statements.vb ' ' Tests should be added here for every construct that can be bound ' correctly, with a test that compiles, verifies, and runs code for that construct. ' Tests should also be added here for every diagnostic that can be generated. Public Class Binder_Statements_Tests Inherits BasicTestBase <Fact> Public Sub HelloWorld1() CompileAndVerify( <compilation name="HelloWorld1"> <file name="a.vb"> Module M Sub Main() System.Console.WriteLine("Hello, world!") End Sub End Module </file> </compilation>, expectedOutput:="Hello, world!") End Sub <Fact> Public Sub HelloWorld2() CompileAndVerify( <compilation name="HelloWorld2"> <file name="a.vb"> Imports System Module M1 Sub Main() dim x as object x = 42 Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x) End Sub End Module </file> </compilation>, expectedOutput:="Hello, world 135.2 42") End Sub <Fact> Public Sub LocalWithSimpleInitialization() CompileAndVerify( <compilation name="LocalWithSimpleInitialization"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim s As String = "Hello world" Console.WriteLine(s) s = nothing Console.WriteLine(s) Dim i As Integer = 1 Console.WriteLine(i) Dim d As Double = 1.5 Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello world 1 1.5 ]]>) End Sub <Fact> Public Sub LocalAsNew() CompileAndVerify( <compilation name="LocalAsNew"> <file name="a.vb"> Imports System Class C Sub New (msg as string) Me.msg = msg End Sub Sub Report() Console.WriteLine(msg) End Sub private msg as string End Class Module M1 Sub Main() dim myC as New C("hello") myC.Report() End Sub End Module </file> </compilation>, expectedOutput:="hello") End Sub <Fact> Public Sub LocalAsNewArrayError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalAsNewArrayError"> <file name="a.vb"> Imports System Class C Sub New() End Sub End Class Module M1 Sub Main() ' Arrays cannot be declared with 'New'. dim c1() as new C() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30053: Arrays cannot be declared with 'New'. dim c1() as new C() ~~~ </expected>) End Sub <Fact> Public Sub LocalAsNewArrayError001() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalAsNewArrayError"> <file name="a.vb"> Imports System Class X Dim a(), b As New S End Class Class X1 Dim a, b() As New S End Class Class X2 Dim a, b(3) As New S End Class Class X3 Dim a, b As New S(){} End Class Structure S End Structure Module M1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30053: Arrays cannot be declared with 'New'. Dim a(), b As New S ~~~ BC30053: Arrays cannot be declared with 'New'. Dim a, b() As New S ~~~ BC30053: Arrays cannot be declared with 'New'. Dim a, b(3) As New S ~~~~ BC30205: End of statement expected. Dim a, b As New S(){} ~ </expected>) End Sub <WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")> <Fact> Public Sub LocalSameNameAsOperatorAllowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalSameNameAsOperatorAllowed"> <file name="a.vb"> Imports System Class C Public Shared Operator IsTrue(ByVal w As C) As Boolean Dim IsTrue As Boolean = True Return IsTrue End Operator Public Shared Operator IsFalse(ByVal w As C) As Boolean Dim IsFalse As Boolean = True Return IsFalse End Operator End Class Module M1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub ParameterlessSub() CompileAndVerify( <compilation name="ParameterlessSub"> <file name="a.vb"> Imports System Module M1 Sub Goo() Console.WriteLine("Hello, world") Console.WriteLine() Console.WriteLine("Goodbye, world") End Sub Sub Main() Goo End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello, world Goodbye, world ]]>) End Sub <Fact> Public Sub CallStatement() CompileAndVerify( <compilation name="CallStatement"> <file name="a.vb"> Imports System Module M1 Sub Goo() Console.WriteLine("Call without parameters") End Sub Sub Goo(s as string) Console.WriteLine(s) End Sub Function SayHi as string return "Hi" End Function Function One as integer return 1 End Function Sub Main() Goo(SayHi) goo call goo call goo("call with parameters") dim i = One + One Console.WriteLine(i) i = One Console.WriteLine(i) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hi Call without parameters Call without parameters call with parameters 2 1 ]]>) End Sub <Fact> Public Sub CallStatementMethodNotFound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodNotFound"> <file name="a.vb"> Imports System Module M1 Sub Main() call goo End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'goo' is not declared. It may be inaccessible due to its protection level. call goo ~~~ </expected>) End Sub <WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")> <Fact> Public Sub CallStatementNothingAsInvocationExpression_Bug_4247() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Module M1 Sub Main() Dim myLocalArr as Integer() Dim myLocalVar as Integer = 42 call myLocalArr(0) call myLocalVar call Nothing call 911 call new Integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. call myLocalArr(0) ~~~~~~~~~~ BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime. call myLocalArr(0) ~~~~~~~~~~ BC30454: Expression is not a method. call myLocalVar ~~~~~~~~~~ BC30454: Expression is not a method. call Nothing ~~~~~~~ BC30454: Expression is not a method. call 911 ~~~ BC30454: Expression is not a method. call new Integer ~~~~~~~~~~~ </expected>) End Sub ' related to bug 4247 <Fact> Public Sub CallStatementNamespaceAsInvocationExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Namespace N1.N2 Module M1 Sub Main() call N1 call N1.N2 End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'N1' is a namespace and cannot be used as an expression. call N1 ~~ BC30112: 'N1.N2' is a namespace and cannot be used as an expression. call N1.N2 ~~~~~ </expected>) End Sub ' related to bug 4247 <WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")> <Fact> Public Sub CallStatementTypeAsInvocationExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CallStatementMethodIsNothing"> <file name="goo.vb"> Class Class1 End Class Module M1 Sub Main() call Class1 call Integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30109: 'Class1' is a class type and cannot be used as an expression. call Class1 ~~~~~~ BC30110: 'Integer' is a structure type and cannot be used as an expression. call Integer ~~~~~~~ </expected>) End Sub <Fact> Public Sub AssignmentStatement() CompileAndVerify( <compilation name="AssignmentStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim s As String s = "Hello world" Console.WriteLine(s) Dim i As Integer i = 1 Console.WriteLine(i) Dim d As Double d = 1.5 Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture)) d = i Console.WriteLine(d) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Hello world 1 1.5 1 ]]>) End Sub <Fact> Public Sub FieldAssignmentStatement() CompileAndVerify( <compilation name="FieldAssignmentStatement"> <file name="a.vb"> Imports System Class C1 public i as integer End class Structure S1 public s as string End Structure Module M1 Sub Main() dim myC as C1 = new C1 myC.i = 10 Console.WriteLine(myC.i) dim myS as S1 = new S1 myS.s = "a" Console.WriteLine(MyS.s) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 10 a ]]>) End Sub <Fact> Public Sub AssignmentWithBadLValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssignmentWithBadLValue"> <file name="a.vb"> Imports System Module M1 Function f as integer return 0 End function Sub s End Sub Sub Main() f = 0 s = 1 dim i as integer End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30068: Expression is a value and therefore cannot be the target of an assignment. f = 0 ~ BC30068: Expression is a value and therefore cannot be the target of an assignment. s = 1 ~ BC42024: Unused local variable: 'i'. dim i as integer ~ </expected>) End Sub <Fact> Public Sub MultilineIfStatement1() CompileAndVerify( <compilation name="MultilineIfStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim cond As Boolean Dim cond2 As Boolean Dim cond3 As Boolean cond = True cond2 = True cond3 = True If cond Then Console.WriteLine("1. ThenPart") End If If cond Then Console.WriteLine("2. ThenPart") Else Console.WriteLine("2. ElsePart") End If If cond Then Console.WriteLine("3. ThenPart") Else If cond2 Console.WriteLine("3. ElseIfPart") End If If cond Then Console.WriteLine("4. ThenPart") Else If cond2 Console.WriteLine("4. ElseIf1Part") Else If cond3 Console.WriteLine("4. ElseIf2Part") Else Console.WriteLine("4. ElsePart") End If cond = False If cond Then Console.WriteLine("5. ThenPart") End If If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart") End If If cond Then Console.WriteLine("7. ThenPart") Else If cond2 Console.WriteLine("7. ElseIfPart") End If If cond Then Console.WriteLine("8. ThenPart") Else If cond2 Console.WriteLine("8. ElseIf1Part") Else If cond3 Console.WriteLine("8. ElseIf2Part") Else Console.WriteLine("8. ElsePart") End If cond2 = false If cond Then Console.WriteLine("9. ThenPart") Else If cond2 Console.WriteLine("9. ElseIfPart") End If If cond Then Console.WriteLine("10. ThenPart") Else If cond2 Console.WriteLine("10. ElseIf1Part") Else If cond3 Console.WriteLine("10. ElseIf2Part") Else Console.WriteLine("10. ElsePart") End If cond3 = false If cond Then Console.WriteLine("11. ThenPart") Else If cond2 Console.WriteLine("11. ElseIf1Part") Else If cond3 Console.WriteLine("11. ElseIf2Part") Else Console.WriteLine("11. ElsePart") End If End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1. ThenPart 2. ThenPart 3. ThenPart 4. ThenPart 6. ElsePart 7. ElseIfPart 8. ElseIf1Part 10. ElseIf2Part 11. ElsePart ]]>) End Sub <Fact> Public Sub SingleLineIfStatement1() CompileAndVerify( <compilation name="SingleLineIfStatement1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim cond As Boolean cond = True If cond Then Console.WriteLine("1. ThenPart") If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB") If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB") If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB") If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart") If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart") cond = false If cond Then Console.WriteLine("7. ThenPart") If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB") If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB") If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB") If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart") If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart") End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1. ThenPart 2. ThenPartA 2. ThenPartB 3. ThenPartA 3. ThenPartB 4. ThenPart 5. ThenPartA 5. ThenPartB 6. ThenPart 9. ElsePartA 9. ElsePartB 10. ElsePartA 10. ElsePartB 11. ElsePart 12. ElsePart ]]>) End Sub <Fact> Public Sub DoLoop1() CompileAndVerify( <compilation name="DoLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = true Do While breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = false Loop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop2() CompileAndVerify( <compilation name="DoLoop2"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false Do Until breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = true Loop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop3() CompileAndVerify( <compilation name="DoLoop3"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = true Do Console.WriteLine("Iterate {0}", x) breakLoop = false Loop While breakLoop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub DoLoop4() CompileAndVerify( <compilation name="DoLoop4"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false Do Console.WriteLine("Iterate {0}", x) breakLoop = true Loop Until breakLoop End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub WhileLoop1() CompileAndVerify( <compilation name="WhileLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x As Integer dim breakLoop as Boolean x = 1 breakLoop = false While not breakLoop Console.WriteLine("Iterate {0}", x) breakLoop = true End While End Sub End Module </file> </compilation>, expectedOutput:="Iterate 1") End Sub <Fact> Public Sub ExitContinueDoLoop1() CompileAndVerify( <compilation name="ExitContinueDoLoop1"> <file name="a.vb"> Imports System Module M1 Sub Main() dim breakLoop as Boolean dim continueLoop as Boolean breakLoop = True: continueLoop = true Do While breakLoop Console.WriteLine("Stmt1") If continueLoop Then Console.WriteLine("Continuing") continueLoop = false Continue Do End If Console.WriteLine("Exiting") Exit Do Console.WriteLine("Stmt2") Loop Console.WriteLine("After Loop") End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Stmt1 Continuing Stmt1 Exiting After Loop ]]>) End Sub <Fact> Public Sub ExitSub() CompileAndVerify( <compilation name="ExitSub"> <file name="a.vb"> Imports System Module M1 Sub Main() dim breakLoop as Boolean breakLoop = True Do While breakLoop Console.WriteLine("Stmt1") Console.WriteLine("Exiting") Exit Sub Console.WriteLine("Stmt2") 'should not output Loop Console.WriteLine("After Loop") 'should not output End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Stmt1 Exiting ]]>) End Sub <Fact> Public Sub ExitFunction() CompileAndVerify( <compilation name="ExitFunction"> <file name="a.vb"> Imports System Module M1 Function Fact(i as integer) as integer fact = 1 do if i &lt;= 0 then exit function else fact = i * fact i = i - 1 end if loop End Function Sub Main() Console.WriteLine(Fact(0)) Console.WriteLine(Fact(3)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 6 ]]>) End Sub <Fact> Public Sub BadExit() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadExit"> <file name="a.vb"> Imports System Module M1 Sub Main() Do Exit Do ' ok Exit For Exit Try Exit Select Exit While Loop Exit Do ' outside loop End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ BC30099: 'Exit Select' can only appear inside a 'Select' statement. Exit Select ~~~~~~~~~~~ BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit Do ' outside loop ~~~~~~~ </expected>) End Sub <Fact> Public Sub BadContinue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadContinue"> <file name="a.vb"> Imports System Module M1 Sub Main() Do Continue Do ' ok Continue For Continue While Loop Continue Do ' outside loop End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30783: 'Continue For' can only appear inside a 'For' statement. Continue For ~~~~~~~~~~~~ BC30784: 'Continue While' can only appear inside a 'While' statement. Continue While ~~~~~~~~~~~~~~ BC30782: 'Continue Do' can only appear inside a 'Do' statement. Continue Do ' outside loop ~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Return1() CompileAndVerify( <compilation name="Return1"> <file name="a.vb"> Imports System Module M1 Function F1 as Integer F1 = 1 End Function Function F2 as Integer if true then F2 = 2 else return 3 end if End Function Function F3 as Integer return 3 End Function Sub S1 return End Sub Sub Main() dim result as integer result = F1() Console.WriteLine(result) result = F2() Console.WriteLine(result) result = F3() Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub <Fact> Public Sub BadReturn() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadReturn"> <file name="a.vb"> Imports System Module M1 Function F1 as Integer return End Function Sub S1 return 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30654: 'Return' statement in a Function, Get, or Operator must return a value. return ~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. return 1 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub NoReturnUnreachableEnd() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoReturnUnreachableEnd"> <file name="a.vb"> Imports System Module M1 Function goo() As Boolean While True End While End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub BadArrayInitWithExplicitArraySize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(3) as integer = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. dim a(3) as integer = 1 ~~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer()'. dim a(3) as integer = 1 ~ </expected>) End Sub <Fact> Public Sub BadArrayWithNegativeSize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayWithNegativeSize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(-3) as integer dim b = new integer(-3){} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. dim a(-3) as integer ~~ BC30611: Array dimensions cannot have a negative size. dim b = new integer(-3){} ~~ </expected>) End Sub <Fact> Public Sub ArrayWithMinusOneUpperBound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayWithNegativeSize"> <file name="a.vb"> Imports System Module M1 Sub S1 dim a(-1) as integer dim b = new integer(-1){} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")> <Fact()> Public Sub MultiDimensionalArrayWithTooFewInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiDimensionalArrayWithTooFewInitializers"> <file name="Program.vb"> Module Program Sub Main() Dim x = New Integer(0, 1) {{}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30567: Array initializer is missing 2 elements. Dim x = New Integer(0, 1) {{}} ~~ </expected>) End Sub <WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")> <Fact()> Public Sub Max32ArrayDimensionsAreAllowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Max32ArrayDimensionsAreAllowed"> <file name="Program.vb"> Module Program Sub Main() Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {} Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {} Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {} Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {} End Sub End Module </file> </compilation>). VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"), Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"), Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)")) End Sub <Fact> Public Sub GotoIf() CompileAndVerify( <compilation name="GotoIf"> <file name="a.vb"> Imports System Module M1 Sub GotoIf() GoTo l1 If False Then l1: Console.WriteLine("Jump into If") End If End Sub Sub GotoWhile() GoTo l1 While False l1: Console.WriteLine("Jump into While") End While End Sub Sub GotoDo() GoTo l1 Do While False l1: Console.WriteLine("Jump into Do") Loop End Sub Sub GotoSelect() Dim i As Integer = 0 GoTo l1 Select Case i Case 0 l1: Console.WriteLine("Jump into Select") End Select End Sub Sub Main() GotoIf() GotoWhile() GotoDo() GotoSelect() End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Jump into If Jump into While Jump into Do Jump into Select ]]>) End Sub <Fact()> Public Sub GotoIntoBlockErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoBlockErrors"> <file name="a.vb"> Imports System Module M1 Sub GotoFor() For i as Integer = 0 To 10 l1: Console.WriteLine() Next GoTo l1 End Sub Sub GotoWith() Dim c1 = New C() With c1 l1: Console.WriteLine() End With GoTo l1 End Sub Sub GotoUsing() Using c1 as IDisposable = nothing l1: Console.WriteLine() End Using GoTo l1 End Sub Sub GotoTry() Try l1: Console.WriteLine() Finally End Try GoTo l1 End Sub Sub GotoLambda() Dim x = Sub() l1: End Sub GoTo l1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo l1 ~~ BC30002: Type 'C' is not defined. Dim c1 = New C() ~ BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement. GoTo l1 ~~ BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement. GoTo l1 ~~ BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo l1 ~~ BC30132: Label 'l1' is not defined. GoTo l1 ~~ </expected>) End Sub <Fact()> Public Sub GotoDecimalLabels() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoDecimalLabels"> <file name="a.vb"> Imports System Module M Sub Main() 1 : Goto &amp;H2 2 : Goto 01 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")> <Fact()> Public Sub GotoUndefinedLabel() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoUndefinedLabel"> <file name="a.vb"> Imports System Class c1 Shared Sub Main() GoTo lab1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30132: Label 'lab1' is not defined. GoTo lab1 ~~~~ </expected>) End Sub <WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")> <Fact()> Public Sub ArrayModifiersOnVariableAndType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayModifiersOnVariableAndType"> <file name="a.vb"> Imports System Module M1 public a() as integer() public b(1) as integer() Sub S1 dim a() as integer() = nothing dim b(1) as string() End Sub Sub S2(x() as integer()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31087: Array modifiers cannot be specified on both a variable and its type. public a() as integer() ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. public b(1) as integer() ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. dim a() as integer() = nothing ~~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. dim b(1) as string() ~~~~~~~~ BC31087: Array modifiers cannot be specified on both a variable and its type. Sub S2(x() as integer()) ~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Bug6663() ' Test dependent on referenced mscorlib, but NOT system.dll. Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="Bug6663"> <file name="a.vb"> Imports System Module Program Sub Main() Console.WriteLine("".ToString() = "".ToString()) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:="True") End Sub <WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")> <Fact()> Public Sub Bug6637() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Option Infer Off Imports System Module M1 Sub Main() Dim a(3) As Integer For i = 0 To 3 Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'i' is not declared. It may be inaccessible due to its protection level. For i = 0 To 3 ~ </expected>) End Sub <WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")> <Fact()> Public Sub Bug6662() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadArrayInitWithExplicitArraySize"> <file name="a.vb"> Option Infer Off Class C Shared Sub M() For i = Nothing To 10 Dim d as System.Action = Sub() i = i + 1 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'i' is not declared. It may be inaccessible due to its protection level. For i = Nothing To 10 ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Dim d as System.Action = Sub() i = i + 1 ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Dim d as System.Action = Sub() i = i + 1 ~ </expected>) End Sub <WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")> <Fact()> Public Sub ExtTryFromFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Try End Try Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {SystemCoreRef}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchNotLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotLocal"> <file name="goo.vb"> Module M1 Private ex as System.Exception Sub Main() Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")> Public Sub Bug651622() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="goo.vb"> Module Module1 Sub Main() Try Catch Main Catch x as System.Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch Main ~~~~ </expected>) End Sub <Fact()> Public Sub CatchStatic() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchStatic"> <file name="goo.vb"> Imports System Module M1 Sub Main() Static ex as exception = nothing Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <Fact()> Public Sub CatchUndeclared() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchUndeclared"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Main() Try ' Explicit off does not have effect on Catch - ex is still undefined. Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'ex' is not declared. It may be inaccessible due to its protection level. Catch ex ~~ </expected>) End Sub <Fact()> Public Sub CatchNotException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Main() Dim ex as String = "qq" Try Catch ex End Try Try Catch ex1 as String End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch ex ~~ BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch ex1 as String ~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchNotVariableOrParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotVariableOrParameter"> <file name="goo.vb"> Option Explicit Off Module M1 Sub Goo End Sub Sub Main() Try Catch Goo End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch Goo ~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try Catch ex Catch ex1 as Exception Catch End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ~~~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try Catch Catch ex Catch ex1 as Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex ~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchDuplicate2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex as Exception = Nothing Try ' the following is NOT considered as catching all System.Exceptions Catch When true Catch ex ' filter does NOT make this reachable. Catch ex1 as Exception When true ' implicitly this is a "Catch ex As Exception When true" so still unreachable Catch When true Catch ex1 as Exception End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception When true ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch When true ~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 as Exception ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchOverlapped() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim ex As SystemException = Nothing Try ' the following is NOT considered as catching all System.Exceptions Catch When True Catch ex ' filter does NOT make this reachable. Catch ex1 As ArgumentException When True ' implicitly this is a "Catch ex As Exception When true" Catch When True ' this is ok since it is not derived from SystemException ' and catch above has a filter Catch ex1 As ApplicationException End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'. Catch ex1 As ArgumentException When True ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub CatchShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Dim field As String Function Goo(Of T)(ex As Exception) As Exception Dim ex1 As SystemException = Nothing Try Dim ex2 As Exception = nothing Catch ex As Exception Catch ex1 As Exception Catch Goo As ArgumentException When True ' this is ok Catch ex2 As exception Dim ex3 As exception = nothing 'this is ok Catch ex3 As ApplicationException ' this is ok Catch field As Exception End Try return nothing End Function Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'ex' is already declared as a parameter of this method. Catch ex As Exception ~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex1 As Exception ~~~~~~~~~~~~~~~~~~~~~~ BC30616: Variable 'ex1' hides a variable in an enclosing block. Catch ex1 As Exception ~~~ BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'. Catch Goo As ArgumentException When True ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30290: Local variable cannot have the same name as the function containing it. Catch Goo As ArgumentException When True ~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ex2 As exception ~~~~~~~~~~~~~~~~~~~~~~ BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'. Catch ex3 As ApplicationException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch field As Exception ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")> <Fact()> Public Sub CatchShadowingGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException"> <file name="goo.vb"> Imports System Module M1 Class cls3(Of T As NullReferenceException) Sub scen3() Try Catch ex As T Catch ex As NullReferenceException End Try End Sub Sub scen4() Try Catch ex As NullReferenceException 'COMPILEWarning: BC42029 ,"Catch ex As T" Catch ex As T End Try End Sub End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'. Catch ex As T ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub GotoOutOfFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoOutOfFinally"> <file name="goo.vb"> Imports System Module M1 Sub Main() l1: Try Finally try goto l1 catch End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. goto l1 ~~ </expected>) End Sub <Fact()> Public Sub BranchOutOfFinally1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BranchOutOfFinally1"> <file name="goo.vb"> Imports System Module M1 Sub Main() for i as integer = 1 to 10 Try Finally continue for End Try Next End Sub Function Goo() as integer l1: Try Finally try return 1 catch return 1 End Try End Try End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. continue for ~~~~~~~~~~~~ BC30101: Branching out of a 'Finally' is not valid. return 1 ~~~~~~~~ BC30101: Branching out of a 'Finally' is not valid. return 1 ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub GotoFromCatchToTry() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoFromCatchToTry"> <file name="goo.vb"> Imports System Module M1 Sub Main() Try Catch ex As Exception l1: Try GoTo l1 Catch ex2 As Exception GoTo l1 Finally End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub GotoFromCatchToTry1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoFromCatchToTry"> <file name="goo.vb"> Imports System Module M1 Sub Main() Try l1: Catch ex As Exception Try GoTo l1 Catch ex2 As Exception GoTo l1 Finally End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub UnassignedVariableInLateAddressOf() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter"> <file name="goo.vb"> Option Strict Off Imports System Module Program Delegate Sub d1(ByRef x As Integer, y As Integer) Sub Main() Dim obj As Object '= New cls1 Dim o As d1 = AddressOf obj.goo Dim l As Integer = 0 o(l, 2) Console.WriteLine(l) End Sub Class cls1 Shared Sub goo(ByRef x As Integer, y As Integer) x = 42 Console.WriteLine(x + y) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Dim o As d1 = AddressOf obj.goo ~~~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Dim B as StackOverflowException Dim C as Exception Try A = new ApplicationException B = new StackOverflowException C = new Exception Console.Writeline(A) 'this is ok Catch ex as NullReferenceException When A.Message isnot nothing Catch ex as DivideByZeroException Console.Writeline(B) Finally Console.Writeline(C) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Catch ex as NullReferenceException When A.Message isnot nothing ~ BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(B) ~ BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(C) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter1"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try ' ok , A is assigned in the filter and in the catch Catch A When A.Message isnot nothing Console.Writeline(A) Catch ex as Exception A = new ApplicationException Finally 'error Console.Writeline(A) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter2"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch End Try Console.Writeline(A) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter3"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch try Finally A = new ApplicationException End Try End Try Console.Writeline(A) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub UnassignedVariableInCatchFinallyFilter4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnassignedVariableInCatchFinallyFilter4"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim A as ApplicationException Try A = new ApplicationException Catch A Catch try Finally A = new ApplicationException End Try Finally Console.Writeline(A) End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime. Console.Writeline(A) ~ </expected>) End Sub <Fact()> Public Sub ThrowNotValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly Property Moo As Exception Get Return New Exception End Get End Property WriteOnly Property Boo As Exception Set(value As Exception) End Set End Property Sub Main() Throw Moo Throw Boo End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'Boo' is 'WriteOnly'. Throw Boo ~~~ </expected>) End Sub <Fact()> Public Sub ThrowNotException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly e as new Exception ReadOnly s as string = "qq" Sub Main() Throw e Throw s End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw s ~~~~~~~ </expected>) End Sub <Fact()> Public Sub RethrowNotInCatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RethrowNotInCatch"> <file name="goo.vb"> Imports System Module M1 Sub Main() Throw Try Throw Catch ex As Exception Throw Dim a As Action = Sub() ex.ToString() Throw End Sub Try Throw Catch Throw Finally Throw End Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ </expected>) End Sub <Fact()> Public Sub ForNotValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ThrowNotValue"> <file name="goo.vb"> Imports System Module M1 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Moo = 1 to Moo step Moo ~~~ BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Boo = 1 to Boo step Boo ~~~ BC30524: Property 'Boo' is 'WriteOnly'. For Boo = 1 to Boo step Boo ~~~ BC30524: Property 'Boo' is 'WriteOnly'. For Boo = 1 to Boo step Boo ~~~ </expected>) End Sub <Fact()> Public Sub CustomDatatypeForLoop() Dim source = <compilation> <file name="goo.vb"><![CDATA[ Imports System Module Module1 Public Sub Main() Dim x As New c1 For x = 1 To 3 Console.WriteLine("hi") Next End Sub End Module Public Class c1 Public val As Integer Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1 Console.WriteLine("c1::CType(Integer) As c1") Dim c As New c1 c.val = arg1 'what happens if this is last statement? Return c End Operator Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer Console.WriteLine("c1::CType(c1) As Integer") Dim x As Integer x = arg1.val Return x End Operator Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1 Console.WriteLine("c1::+(c1, c1) As c1") Dim c As New c1 c.val = arg1.val + arg2.val Return c End Operator Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1 Console.WriteLine("c1::-(c1, c1) As c1") Dim c As New c1 c.val = arg1.val - arg2.val Return c End Operator Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean Console.WriteLine("c1::>=(c1, Integer) As Boolean") If arg1.val >= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean Console.WriteLine("c1::<=(c1, Integer) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean Console.WriteLine("c1::<=(Integer, c1) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean Console.WriteLine("c1::>=(Integer, c1) As Boolean") If arg1.val <= arg2 Then Return True Else Return False End If End Operator Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean Console.WriteLine("c1::<=(c1, c1) As Boolean") If arg1.val <= arg2.val Then Return True Else Return False End If End Operator Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean Console.WriteLine("c1::>=(c1, c1) As Boolean") If arg1.val >= arg2.val Then Return True Else Return False End If End Operator End Class ]]> </file> </compilation> CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1 c1::CType(Integer) As c1 c1::CType(Integer) As c1 c1::-(c1, c1) As c1 c1::>=(c1, c1) As Boolean c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean hi c1::+(c1, c1) As c1 c1::<=(c1, c1) As Boolean ]]>) End Sub <Fact()> Public Sub SelectCase1_SwitchTable() CompileAndVerify( <compilation name="SelectCase1"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) Select Case number Case 0 Console.WriteLine("Equal to 0") Case 1, 2, 3, 4, 5 Console.WriteLine("Between 1 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9, 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[0:Equal to 0 1:Between 1 and 5, inclusive 2:Between 1 and 5, inclusive 3:Between 1 and 5, inclusive 4:Between 1 and 5, inclusive 5:Between 1 and 5, inclusive 6:Between 6 and 8, inclusive 7:Between 6 and 8, inclusive 8:Between 6 and 8, inclusive 9:Equal to 9 or 10 10:Equal to 9 or 10 11:Greater than 10]]>) End Sub <Fact()> Public Sub SelectCase2_IfList() CompileAndVerify( <compilation name="SelectCase2"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) Select Case number Case Is < 1 Console.WriteLine("Less than 1") Case 1 To 5 Console.WriteLine("Between 1 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[0:Less than 1 1:Between 1 and 5, inclusive 2:Between 1 and 5, inclusive 3:Between 1 and 5, inclusive 4:Between 1 and 5, inclusive 5:Between 1 and 5, inclusive 6:Between 6 and 8, inclusive 7:Between 6 and 8, inclusive 8:Between 6 and 8, inclusive 9:Equal to 9 or 10 10:Equal to 9 or 10 11:Greater than 10]]>) End Sub <WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")> <Fact()> Public Sub ImplicitVarInRedim() CompileAndVerify( <compilation name="HelloWorld1"> <file name="a.vb"> Option Explicit Off Module M Sub Main() Redim x(10) System.Console.WriteLine("OK") End Sub End Module </file> </compilation>, expectedOutput:="OK") End Sub <Fact()> Public Sub EndStatementsInMethodBodyShouldNotThrowNYI() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EndStatementsInMethodBodyShouldNotThrowNYI"> <file name="a.vb"> Namespace N1 Public Class C1 Public Sub S1() for i as integer = 23 to 42 next next do loop while true loop end if end select end try end using end while end with end synclock Try Catch ex As System.Exception End Try catch Try Catch ex As System.Exception finally finally End Try finally End Sub Public Sub S2 end namespace end module end class end structure end interface end enum end function end operator end property end get end set end event end addhandler end removehandler end raiseevent End Sub end Class end Namespace Namespace N2 Class C2 function F1() as integer end sub return 42 end function End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30481: 'Class' statement must end with a matching 'End Class'. Public Class C1 ~~~~~~~~~~~~~~~ BC30092: 'Next' must be preceded by a matching 'For'. next ~~~~ BC30091: 'Loop' must be preceded by a matching 'Do'. loop ~~~~ BC30087: 'End If' must be preceded by a matching 'If'. end if ~~~~~~ BC30088: 'End Select' must be preceded by a matching 'Select Case'. end select ~~~~~~~~~~ BC30383: 'End Try' must be preceded by a matching 'Try'. end try ~~~~~~~ BC36007: 'End Using' must be preceded by a matching 'Using'. end using ~~~~~~~~~ BC30090: 'End While' must be preceded by a matching 'While'. end while ~~~~~~~~~ BC30093: 'End With' must be preceded by a matching 'With'. end with ~~~~~~~~ BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'. end synclock ~~~~~~~~~~~~ BC30380: 'Catch' cannot appear outside a 'Try' statement. catch ~~~~~ BC30381: 'Finally' can only appear once in a 'Try' statement. finally ~~~~~~~ BC30382: 'Finally' cannot appear outside a 'Try' statement. finally ~~~~~~~ BC30026: 'End Sub' expected. Public Sub S2 ~~~~~~~~~~~~~ BC30622: 'End Module' must be preceded by a matching 'Module'. end module ~~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. end class ~~~~~~~~~ BC30621: 'End Structure' must be preceded by a matching 'Structure'. end structure ~~~~~~~~~~~~~ BC30252: 'End Interface' must be preceded by a matching 'Interface'. end interface ~~~~~~~~~~~~~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. end enum ~~~~~~~~ BC30430: 'End Function' must be preceded by a matching 'Function'. end function ~~~~~~~~~~~~ BC33007: 'End Operator' must be preceded by a matching 'Operator'. end operator ~~~~~~~~~~~~ BC30431: 'End Property' must be preceded by a matching 'Property'. end property ~~~~~~~~~~~~ BC30630: 'End Get' must be preceded by a matching 'Get'. end get ~~~~~~~ BC30632: 'End Set' must be preceded by a matching 'Set'. end set ~~~~~~~ BC31123: 'End Event' must be preceded by a matching 'Custom Event'. end event ~~~~~~~~~ BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration. end addhandler ~~~~~~~~~~~~~~ BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration. end removehandler ~~~~~~~~~~~~~~~~~ BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration. end raiseevent ~~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End Sub ~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. end Class ~~~~~~~~~ BC30623: 'End Namespace' must be preceded by a matching 'Namespace'. end Namespace ~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. end sub ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub AddHandlerMissingStuff() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") AddHandler v.DomainUnload, AddHandler , del AddHandler End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30201: Expression expected. AddHandler v.DomainUnload, ~ BC30201: Expression expected. AddHandler , del ~ BC30196: Comma expected. AddHandler ~ BC30201: Expression expected. AddHandler ~ BC30201: Expression expected. AddHandler ~ </expected>) End Sub <Fact()> Public Sub AddHandlerUninitialized() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() ' no warnings here, variable is used Dim del As System.EventHandler ' warning here Dim v = AppDomain.CreateDomain("qq") AddHandler v.DomainUnload, del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime. AddHandler v.DomainUnload, del ~~~ </expected>) End Sub <Fact()> Public Sub AddHandlerNotSimple() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") ' real event with arg list AddHandler (v.DomainUnload()), del ' not an event AddHandler (v.GetType()), del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name. AddHandler (v.DomainUnload()), del ~~~~~~~~~~~~~~~~ BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name. AddHandler (v.GetType()), del ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub RemoveHandlerLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module MyClass1 Sub Main(args As String()) Dim v = AppDomain.CreateDomain("qq") RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload") AppDomain.Unload(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event. RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub RemoveHandlerNotEvent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") ' not an event AddHandler (v.GetType), del ' not anything AddHandler v.GetTyp, del End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'GetType' is not an event of 'AppDomain'. AddHandler (v.GetType), del ~~~~~~~ BC30456: 'GetTyp' is not a member of 'AppDomain'. AddHandler v.GetTyp, del ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AddHandlerNoConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddHandlerNotSimple"> <file name="goo.vb"> Imports System Module M1 Sub Main() Dim v = AppDomain.CreateDomain("qq") AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload") AddHandler v.DomainUnload, AddressOf H Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload") AddHandler v.DomainUnload, del End Sub Sub H(i as integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'. AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'. AddHandler v.DomainUnload, AddressOf H ~ BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'. AddHandler v.DomainUnload, del ~~~ </expected>) End Sub <Fact()> Public Sub LegalGotoCasesTryCatchFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LegalGotoCasesTryCatchFinally"> <file name="a.vb"> Module M1 Sub Main() dim x1 = function() labelOK6: goto labelok7 if true then goto labelok6 labelok7: end if return 23 end function dim x2 = sub() labelOK8: goto labelok9 if true then goto labelok8 labelok9: end if end sub Try Goto LabelOK1 LabelOK1: Catch Goto LabelOK2 LabelOK2: Try goto LabelOK1 goto LabelOK2: LabelOK5: Catch goto LabelOK1 goto LabelOK5 goto LabelOK2 Finally End Try Finally Goto LabelOK3 LabelOK3: End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")> <Fact()> Public Sub Bug10583() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LegalGotoCasesTryCatchFinally"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Try GoTo label GoTo label5 Catch ex As Exception label: Finally label5: End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label ~~~~~ BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label5 ~~~~~~ </expected>) End Sub <WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")> <Fact()> Public Sub SelectCase_ImplicitOperator() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase"> <file name="a.vb"><![CDATA[ Imports System Module M1 Class X Public Shared Operator =(left As X, right As X) As Boolean Return True End Operator Public Shared Operator <>(left As X, right As X) As Boolean Return True End Operator Public Shared Widening Operator CType(expandedName As String) As X Return New X() End Operator End Class Sub Main() End Sub Sub Test(x As X) Select Case x Case "a" Console.WriteLine("Equal to a") Case "s" Console.WriteLine("Equal to A") Case "3" Console.WriteLine("Error") Case "5" Console.WriteLine("Error") Case "6" Console.WriteLine("Error") Case "9" Console.WriteLine("Error") Case "11" Console.WriteLine("Error") Case "12" Console.WriteLine("Error") Case "13" Console.WriteLine("Error") Case Else Console.WriteLine("Error") End Select End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> </expected>) End Sub <WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")> <Fact()> Public Sub Binding_Return_As_Declaration() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="SelectCase"> <file name="a.vb"><![CDATA[ Class Program Shared Main() Return Nothing End sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30689: Statement cannot appear outside of a method body. Return Nothing ~~~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End sub ~~~~~~~ </expected>) End Sub <WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")> <Fact> Public Sub WhileOutOfMethod() Dim source = <compilation> <file name="a.vb"> While (true) </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)")) End Sub <WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")> <Fact> Public Sub WhileOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 While (true) End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)")) End Sub <WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")> <Fact> Public Sub IfOutOfMethod() Dim source = <compilation> <file name="a.vb"> If (true) </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)")) End Sub <WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")> <Fact> Public Sub IfOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 If (true) End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)")) End Sub <WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")> <Fact> Public Sub TryOutOfMethod() Dim source = <compilation> <file name="a.vb"> Try Catch </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch")) End Sub <WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")> <Fact> Public Sub TryOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Try Catch End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch")) End Sub <WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")> <Fact> Public Sub DoOutOfMethod() Dim source = <compilation> <file name="a.vb"> Do </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do")) End Sub <WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")> <Fact> Public Sub DoOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Do End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do")) End Sub <WorkItem(11031, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseOutOfMethod() Dim source = <compilation> <file name="a.vb"> Else </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else")) End Sub <WorkItem(11031, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseOutOfMethod_1() Dim source = <compilation> <file name="a.vb"> Class c1 Else End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else")) End Sub <WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")> <Fact()> Public Sub DuplicateNullableLocals() Dim source = <compilation> <file name="a.vb"> Option Explicit Off Module M Sub S() Dim A? As Integer = 1 Dim A? As Integer? = 1 End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"), Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A")) End Sub <WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")> <Fact()> Public Sub IllegalModifiers() Dim source = <compilation> <file name="a.vb"> Class C Public Custom E End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom")) End Sub <Fact()> Public Sub InvalidCode_ConstInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Const Interface </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC30397: 'Const' is not valid on an Interface declaration. Const Interface ~~~~~ BC30253: 'Interface' must end with a matching 'End Interface'. Const Interface ~~~~~~~~~~~~~~~ BC30203: Identifier expected. Const Interface ~ </errors>) End Sub <WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")> <Fact()> Public Sub InvalidCode_Event() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Event </file> </compilation>) compilation.AssertTheseParseDiagnostics(<errors> BC30203: Identifier expected. Event ~ </errors>) End Sub <Fact> Public Sub StopAndEnd_1() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Public Sub Main() Dim m = GetType(Module1) System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags) System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags) System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags) Try System.Console.WriteLine("Before End") TestEnd() System.Console.WriteLine("After End") Finally System.Console.WriteLine("In Finally") End Try System.Console.WriteLine("After Try") End Sub Sub TestEnd() End End Sub Sub TestStop() Stop End Sub Sub Dummy() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, symbolValidator:=Sub(m As ModuleSymbol) Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization, DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes) Assert.Equal(MethodImplAttributes.Managed, DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes) Assert.Equal(MethodImplAttributes.Managed, DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes) End Sub) compilationVerifier.VerifyIL("Module1.TestEnd", <![CDATA[ { // Code size 6 (0x6) .maxstack 0 IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()" IL_0005: ret } ]]>) compilationVerifier.VerifyIL("Module1.TestStop", <![CDATA[ { // Code size 6 (0x6) .maxstack 0 IL_0000: call "Sub System.Diagnostics.Debugger.Break()" IL_0005: ret } ]]>) compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)) AssertTheseDiagnostics(compilation, <expected> BC30615: 'End' statement cannot be used in class library projects. End ~~~ </expected>) End Sub <Fact> Public Sub StopAndEnd_2() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Public Sub Main() Dim x As Object Dim y As Object Stop x.ToString() End y.ToString() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.ToString() ~ </expected>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub StopAndEnd_3() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public state As Integer = 0 Public Sub Main() On Error GoTo handler Throw New NullReferenceException() Stop Console.WriteLine("Done") Return handler: Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType()) If state = 1 Then Resume End If Resume Next End Sub End Module Namespace System.Diagnostics Public Class Debugger Public Shared Sub Break() Console.WriteLine("In Break") Select Case Module1.state Case 0, 1 Module1.state += 1 Case Else Console.WriteLine("Test issue!!!") Return End Select Throw New NotSupportedException() End Sub End Class End Namespace ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:= <![CDATA[ System.NullReferenceException In Break System.NotSupportedException In Break System.NotSupportedException Done ]]>) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithSingleLineIf() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithSingleLineIfWithDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC30615: 'End' statement cannot be used in class library projects. If True Then End Else Console.WriteLine("Test") ~~~ </expected>) End Sub <WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")> <Fact> Public Sub EndWithMultiLineIf() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() If True Then End Else Console.WriteLine("Test") End If End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation) End Sub <WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")> <Fact> Public Sub Regress660010() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class C Inherits value End C ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences) AssertTheseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class C ~~~~~~~ BC30002: Type 'value' is not defined. Inherits value ~~~~~ BC30678: 'End' statement not valid. End C ~~~ </expected>) End Sub <WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")> <Fact> Public Sub NotYetImplementedStatement() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class C Sub M() Inherits A Implements I Imports X Option Strict On End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) AssertTheseDiagnostics(compilation, <expected> BC30024: Statement is not valid inside a method. Inherits A ~~~~~~~~~~ BC30024: Statement is not valid inside a method. Implements I ~~~~~~~~~~~~ BC30024: Statement is not valid inside a method. Imports X ~~~~~~~~~ BC30024: Statement is not valid inside a method. Option Strict On ~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InaccessibleRemoveAccessor() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action TestEvent .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::add_Test .method family specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module Class E2 Inherits E1 Sub Main() Dim d As System.Action = Nothing AddHandler Test, d RemoveHandler Test, d End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InaccessibleAddAccessor() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .field private class [mscorlib]System.Action TestEvent .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method family specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass [mscorlib]System.Action IL_0012: stfld class [mscorlib]System.Action E1::TestEvent IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module Class E2 Inherits E1 Sub Main() Dim d As System.Action = Nothing AddHandler Test, d RemoveHandler Test, d End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'. AddHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub EventTypeIsNotADelegate() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class E1 obj) cil managed synchronized { IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class E1 obj) cil managed synchronized { IL_0017: ret } // end of method E1::remove_Test .event E1 Test { .addon instance void E1::add_Test(class E1) .removeon instance void E1::remove_Test(class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC37223: 'Public Event Test As E1' is an unsupported event. AddHandler e.Test, e ~~~~~~ BC37223: 'Public Event Test As E1' is an unsupported event. RemoveHandler e.Test, e ~~~~~~ </expected>) 'CompileAndVerify(compilation) End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_01() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class E1 obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class E1) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_02() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test() cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test() .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidAddAccessor_03() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action, class E1) .removeon instance void E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d AddHandler e.Test, e RemoveHandler e.Test, e End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, d ~~~~~~ BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. AddHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="remove_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_01() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class E1 obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_02() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test() cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test() } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub InvalidRemoveAccessor_03() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance void add_Test(class [mscorlib]System.Action obj1) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::add_Test .method public specialname instance void remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance void E1::add_Test(class [mscorlib]System.Action) .removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, e RemoveHandler e.Test, e RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30311: Value of type 'E1' cannot be converted to 'Action'. AddHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, e ~~~~~~ BC30311: Value of type 'E1' cannot be converted to 'Action'. RemoveHandler e.Test, e ~ BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported. RemoveHandler e.Test, d ~~~~~~ </expected>) 'CompileAndVerify(compilation1) Dim compilationDef2 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation2, expectedOutput:="add_Test") End Sub <Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")> Public Sub NonVoidAccessors() Dim ilSource = <![CDATA[ .class public auto ansi E1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method E1::.ctor .method public specialname instance int32 add_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "add_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0016: ldc.i4.0 IL_0017: ret } // end of method E1::add_Test .method public specialname instance int32 remove_Test(class [mscorlib]System.Action obj) cil managed synchronized { IL_0008: ldstr "remove_Test" IL_000d: call void [mscorlib]System.Console::WriteLine(string) IL_0016: ldc.i4.0 IL_0017: ret } // end of method E1::remove_Test .event [mscorlib]System.Action Test { .addon instance int32 E1::add_Test(class [mscorlib]System.Action) .removeon instance int32 E1::remove_Test(class [mscorlib]System.Action) } // end of event E1::Test } // end of class E1 ]]> Dim compilationDef1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim e = New E1() Dim d As System.Action = Nothing AddHandler e.Test, d RemoveHandler e.Test, d End Sub End Module </file> </compilation> Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation1, expectedOutput:="add_Test remove_Test") End Sub ''' <summary> ''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name, ''' but is instead parsed as a statement separator when it immediately follows an XML name. ''' If the next token is an identifier or keyword, it should be parsed as a separate statement. ''' An XML name should never include more than one colon. ''' See also: http://fileformat.info/info/unicode/char/FF1A ''' </summary> <Fact> <WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")> Public Sub FullWidthColonInXmlNames() ' FULLWIDTH COLON is represented by "~" below Dim source = <![CDATA[ Imports System Module M Sub Main() Test1() Test2() Test3() Test4() Test5() Test6() Test7() Test8() End Sub Sub Test1() Console.WriteLine(">1") Dim x = <a/>.@xml:goo Console.WriteLine("<1") End Sub Sub Test2() Console.WriteLine(">2") Dim x = <a/>.@xml:goo:goo Console.WriteLine("<2") End Sub Sub Test3() Console.WriteLine(">3") Dim x = <a/>.@xml:return Console.WriteLine("<3") End Sub Sub Test4() Console.WriteLine(">4") Dim x = <a/>.@xml:return:return Console.WriteLine("<4") End Sub Sub Test5() Console.WriteLine(">5") Dim x = <a/>.@xml~goo Console.WriteLine("<5") End Sub Sub Test6() Console.WriteLine(">6") Dim x = <a/>.@xml~return Console.WriteLine("<6") End Sub Sub Test7() Console.WriteLine(">7") Dim x = <a/>.@xml~goo~return Console.WriteLine("<7") End Sub Sub Test8() Console.WriteLine(">8") Dim x = <a/>.@xml~REM Console.WriteLine("<8") End Sub Sub goo Console.WriteLine("goo") End Sub Sub [return] Console.WriteLine("return") End Sub Sub [REM] Console.WriteLine("REM") End Sub End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="FullWidthColonInXmlNames"> <file name="M.vb"><%= source %></file> </compilation>, XmlReferences, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[ >1 <1 >2 goo <2 >3 <3 >4 >5 goo <5 >6 >7 goo >8 <8]]>.Value.Replace(vbLf, Environment.NewLine)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Compilers/CSharp/Portable/BoundTree/BoundTreeVisitors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core.Wpf/EditAndContinue/EditAndContinueErrorTypeFormatDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(EditAndContinueErrorTypeDefinition.Name)] [UserVisible(true)] internal sealed class EditAndContinueErrorTypeFormatDefinition : EditorFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueErrorTypeFormatDefinition() { this.ForegroundBrush = Brushes.Purple; this.BackgroundCustomizable = false; this.DisplayName = EditorFeaturesResources.Rude_Edit; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(EditAndContinueErrorTypeDefinition.Name)] [UserVisible(true)] internal sealed class EditAndContinueErrorTypeFormatDefinition : EditorFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueErrorTypeFormatDefinition() { this.ForegroundBrush = Brushes.Purple; this.BackgroundCustomizable = false; this.DisplayName = EditorFeaturesResources.Rude_Edit; } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/Core/Portable/ChangeSignature/IUnifiedArgumentSyntax.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.ChangeSignature { internal interface IUnifiedArgumentSyntax { bool IsDefault { get; } bool IsNamed { get; } string GetName(); IUnifiedArgumentSyntax WithName(string name); IUnifiedArgumentSyntax WithAdditionalAnnotations(SyntaxAnnotation annotation); } }
// Licensed to the .NET Foundation under one or more 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.ChangeSignature { internal interface IUnifiedArgumentSyntax { bool IsDefault { get; } bool IsNamed { get; } string GetName(); IUnifiedArgumentSyntax WithName(string name); IUnifiedArgumentSyntax WithAdditionalAnnotations(SyntaxAnnotation annotation); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionValidator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator : SelectionValidator { public CSharpSelectionValidator( SemanticDocument document, TextSpan textSpan, OptionSet options) : base(document, textSpan, options) { } public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken) { if (!ContainsValidSelection) { return NullSelection; } var text = SemanticDocument.Text; var root = SemanticDocument.Root; var model = SemanticDocument.SemanticModel; var doc = SemanticDocument; // go through pipe line and calculate information about the user selection var selectionInfo = GetInitialSelectionInfo(root, text); selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken); selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken); selectionInfo = AssignFinalSpan(selectionInfo, text); selectionInfo = ApplySpecialCases(selectionInfo, text); selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root); // there was a fatal error that we couldn't even do negative preview, return error result if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return new ErrorSelectionResult(selectionInfo.Status); } var controlFlowSpan = GetControlFlowSpan(selectionInfo); if (!selectionInfo.SelectionInExpression) { var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken); if (statementRange == null) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Can_t_determine_valid_range_of_statements_to_extract)); return new ErrorSelectionResult(selectionInfo.Status); } var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken); if (!isFinalSpanSemanticallyValid) { // check control flow only if we are extracting statement level, not expression // level. you can not have goto that moves control out of scope in expression level // (even in lambda) selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Not_all_code_paths_return)); } } return await CSharpSelectionResult.CreateAsync( selectionInfo.Status, selectionInfo.OriginalSpan, selectionInfo.FinalSpan, Options, selectionInfo.SelectionInExpression, doc, selectionInfo.FirstTokenInFinalSpan, selectionInfo.LastTokenInFinalSpan, cancellationToken).ConfigureAwait(false); } private static SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression) { return selectionInfo; } var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if (!expressionNode.IsAnyAssignExpression()) { return selectionInfo; } var assign = (AssignmentExpressionSyntax)expressionNode; // make sure there is a visible token at right side expression if (assign.Right.GetLastToken().Kind() == SyntaxKind.None) { return selectionInfo; } return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)), text); } private static TextSpan GetControlFlowSpan(SelectionInfo selectionInfo) => TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End); private static SelectionInfo AdjustFinalTokensBasedOnContext( SelectionInfo selectionInfo, SemanticModel semanticModel, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // don't need to adjust anything if it is multi-statements case if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement) { return selectionInfo; } // get the node that covers the selection var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); var validNode = Check(semanticModel, node, cancellationToken); if (validNode) { return selectionInfo; } var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken)); if (firstValidNode == null) { // couldn't find any valid node return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_node)) .With(s => s.FirstTokenInFinalSpan = default) .With(s => s.LastTokenInFinalSpan = default); } firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode; return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax) .With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax) .With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true)); } private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text) { var adjustedSpan = GetAdjustedSpan(text, OriginalSpan); var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false); var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false); if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), OriginalSpan = adjustedSpan }; } if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span)) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection); if (commonRoot == null) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } if (!commonRoot.ContainedInValidType()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var selectionInExpression = commonRoot is ExpressionSyntax; if (!selectionInExpression && !commonRoot.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } return new SelectionInfo { Status = OperationStatus.Succeeded, OriginalSpan = adjustedSpan, CommonRootFromOriginalSpan = commonRoot, SelectionInExpression = selectionInExpression, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } private static SelectionInfo CheckErrorCasesAndAppendDescriptions( SelectionInfo selectionInfo, SyntaxNode root) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Contains_invalid_selection)); } // get the node that covers the selection var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.The_selection_contains_syntactic_errors)); } var tokens = root.DescendantTokens(selectionInfo.FinalSpan); if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_cross_over_preprocessor_directives)); } // TODO : check whether this can be handled by control flow analysis engine if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_a_yield_statement)); } // TODO : check behavior of control flow analysis engine around exception and exception handling. if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_throw_statement)); } if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_be_part_of_constant_initializer_expression)); } if (commonNode.IsUnsafeContext()) { selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.The_selected_code_is_inside_an_unsafe_context)); } // For now patterns are being blanket disabled for extract method. This issue covers designing extractions for them // and re-enabling this. // https://github.com/dotnet/roslyn/issues/9244 if (commonNode.Kind() == SyntaxKind.IsPatternExpression) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_contain_a_pattern_expression)); } var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan; if (selectionChanged) { selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion()); } return selectionInfo; } private static SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.SelectionInExpression) { // simple expression case return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true)); } var range = GetStatementRangeContainingSpan<StatementSyntax>( root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End), cancellationToken); if (range == null) { return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_statement_range_to_extract)); } var statement1 = (StatementSyntax)range.Item1; var statement2 = (StatementSyntax)range.Item2; if (statement1 == statement2) { // check one more time to see whether it is an expression case var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>(); if (expression != null && statement1.Span.Contains(expression.Span)) { return selectionInfo.With(s => s.SelectionInExpression = true) .With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true)); } // single statement case return selectionInfo.With(s => s.SelectionInSingleStatement = true) .With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true)); } // move only statements inside of the block return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true)); } private static SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // set final span var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ? Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) : selectionInfo.FirstTokenInFinalSpan.FullSpan.Start; var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ? Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) : selectionInfo.LastTokenInFinalSpan.FullSpan.End; return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end))); } public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion) => jumpsOutOfRegion.Where(n => n is not ReturnStatementSyntax).Any(); public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion) { var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax); var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault(); if (container == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault())) .Where(p => p.Item2 != null); // now filter return statements to only include the one under outmost container return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1); } public override bool IsFinalSpanSemanticallyValidSpan( SyntaxNode root, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken) { // return statement shouldn't contain any return value if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null)) { return false; } var lastToken = root.FindToken(textSpan.End); if (lastToken.Kind() == SyntaxKind.None) { return false; } var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { return false; } var body = container.GetBlockBody(); if (body == null) { return false; } // make sure that next token of the last token in the selection is the close braces of containing block if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true)) { return false; } // alright, for these constructs, it must be okay to be extracted switch (container.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return true; } // now, only method is okay to be extracted out if (body.Parent is not MethodDeclarationSyntax method) { return false; } // make sure this method doesn't have return type. return method.ReturnType is PredefinedTypeSyntax p && p.Keyword.Kind() == SyntaxKind.VoidKeyword; } private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan) { // beginning of a file if (textSpan.IsEmpty || textSpan.End == 0) { return textSpan; } // if it is a start of new line, make it belong to previous line var line = text.Lines.GetLineFromPosition(textSpan.End); if (line.Start != textSpan.End) { return textSpan; } // get previous line Contract.ThrowIfFalse(line.LineNumber > 0); var previousLine = text.Lines[line.LineNumber - 1]; // if the span is past the end of the line (ie, in whitespace) then // return to the end of the line including whitespace if (textSpan.Start > previousLine.End) { return TextSpan.FromBounds(textSpan.Start, previousLine.EndIncludingLineBreak); } return TextSpan.FromBounds(textSpan.Start, previousLine.End); } private class SelectionInfo { public OperationStatus Status { get; set; } public TextSpan OriginalSpan { get; set; } public TextSpan FinalSpan { get; set; } public SyntaxNode CommonRootFromOriginalSpan { get; set; } public SyntaxToken FirstTokenInOriginalSpan { get; set; } public SyntaxToken LastTokenInOriginalSpan { get; set; } public SyntaxToken FirstTokenInFinalSpan { get; set; } public SyntaxToken LastTokenInFinalSpan { get; set; } public bool SelectionInExpression { get; set; } public bool SelectionInSingleStatement { get; set; } public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter) => With(s => s.Status = statusGetter(s.Status)); public SelectionInfo With(Action<SelectionInfo> valueSetter) { var newInfo = Clone(); valueSetter(newInfo); return newInfo; } public SelectionInfo Clone() => (SelectionInfo)MemberwiseClone(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator : SelectionValidator { public CSharpSelectionValidator( SemanticDocument document, TextSpan textSpan, OptionSet options) : base(document, textSpan, options) { } public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken) { if (!ContainsValidSelection) { return NullSelection; } var text = SemanticDocument.Text; var root = SemanticDocument.Root; var model = SemanticDocument.SemanticModel; var doc = SemanticDocument; // go through pipe line and calculate information about the user selection var selectionInfo = GetInitialSelectionInfo(root, text); selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken); selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken); selectionInfo = AssignFinalSpan(selectionInfo, text); selectionInfo = ApplySpecialCases(selectionInfo, text); selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root); // there was a fatal error that we couldn't even do negative preview, return error result if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return new ErrorSelectionResult(selectionInfo.Status); } var controlFlowSpan = GetControlFlowSpan(selectionInfo); if (!selectionInfo.SelectionInExpression) { var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken); if (statementRange == null) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Can_t_determine_valid_range_of_statements_to_extract)); return new ErrorSelectionResult(selectionInfo.Status); } var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken); if (!isFinalSpanSemanticallyValid) { // check control flow only if we are extracting statement level, not expression // level. you can not have goto that moves control out of scope in expression level // (even in lambda) selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Not_all_code_paths_return)); } } return await CSharpSelectionResult.CreateAsync( selectionInfo.Status, selectionInfo.OriginalSpan, selectionInfo.FinalSpan, Options, selectionInfo.SelectionInExpression, doc, selectionInfo.FirstTokenInFinalSpan, selectionInfo.LastTokenInFinalSpan, cancellationToken).ConfigureAwait(false); } private static SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression) { return selectionInfo; } var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if (!expressionNode.IsAnyAssignExpression()) { return selectionInfo; } var assign = (AssignmentExpressionSyntax)expressionNode; // make sure there is a visible token at right side expression if (assign.Right.GetLastToken().Kind() == SyntaxKind.None) { return selectionInfo; } return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)), text); } private static TextSpan GetControlFlowSpan(SelectionInfo selectionInfo) => TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End); private static SelectionInfo AdjustFinalTokensBasedOnContext( SelectionInfo selectionInfo, SemanticModel semanticModel, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // don't need to adjust anything if it is multi-statements case if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement) { return selectionInfo; } // get the node that covers the selection var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); var validNode = Check(semanticModel, node, cancellationToken); if (validNode) { return selectionInfo; } var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken)); if (firstValidNode == null) { // couldn't find any valid node return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_node)) .With(s => s.FirstTokenInFinalSpan = default) .With(s => s.LastTokenInFinalSpan = default); } firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode; return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax) .With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax) .With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true)); } private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text) { var adjustedSpan = GetAdjustedSpan(text, OriginalSpan); var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false); var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false); if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), OriginalSpan = adjustedSpan }; } if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span)) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection); if (commonRoot == null) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } if (!commonRoot.ContainedInValidType()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } var selectionInExpression = commonRoot is ExpressionSyntax; if (!selectionInExpression && !commonRoot.UnderValidContext()) { return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction), OriginalSpan = adjustedSpan, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } return new SelectionInfo { Status = OperationStatus.Succeeded, OriginalSpan = adjustedSpan, CommonRootFromOriginalSpan = commonRoot, SelectionInExpression = selectionInExpression, FirstTokenInOriginalSpan = firstTokenInSelection, LastTokenInOriginalSpan = lastTokenInSelection }; } private static SelectionInfo CheckErrorCasesAndAppendDescriptions( SelectionInfo selectionInfo, SyntaxNode root) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Contains_invalid_selection)); } // get the node that covers the selection var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan); if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.The_selection_contains_syntactic_errors)); } var tokens = root.DescendantTokens(selectionInfo.FinalSpan); if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_cross_over_preprocessor_directives)); } // TODO : check whether this can be handled by control flow analysis engine if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_a_yield_statement)); } // TODO : check behavior of control flow analysis engine around exception and exception handling. if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan)) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_throw_statement)); } if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression()) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_be_part_of_constant_initializer_expression)); } if (commonNode.IsUnsafeContext()) { selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.The_selected_code_is_inside_an_unsafe_context)); } // For now patterns are being blanket disabled for extract method. This issue covers designing extractions for them // and re-enabling this. // https://github.com/dotnet/roslyn/issues/9244 if (commonNode.Kind() == SyntaxKind.IsPatternExpression) { selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_contain_a_pattern_expression)); } var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan; if (selectionChanged) { selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion()); } return selectionInfo; } private static SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } if (selectionInfo.SelectionInExpression) { // simple expression case return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true)); } var range = GetStatementRangeContainingSpan<StatementSyntax>( root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End), cancellationToken); if (range == null) { return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_statement_range_to_extract)); } var statement1 = (StatementSyntax)range.Item1; var statement2 = (StatementSyntax)range.Item2; if (statement1 == statement2) { // check one more time to see whether it is an expression case var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>(); if (expression != null && statement1.Span.Contains(expression.Span)) { return selectionInfo.With(s => s.SelectionInExpression = true) .With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true)); } // single statement case return selectionInfo.With(s => s.SelectionInSingleStatement = true) .With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true)); } // move only statements inside of the block return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true)) .With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true)); } private static SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text) { if (selectionInfo.Status.FailedWithNoBestEffortSuggestion()) { return selectionInfo; } // set final span var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ? Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) : selectionInfo.FirstTokenInFinalSpan.FullSpan.Start; var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ? Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) : selectionInfo.LastTokenInFinalSpan.FullSpan.End; return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end))); } public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion) => jumpsOutOfRegion.Where(n => n is not ReturnStatementSyntax).Any(); public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion) { var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax); var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault(); if (container == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault())) .Where(p => p.Item2 != null); // now filter return statements to only include the one under outmost container return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1); } public override bool IsFinalSpanSemanticallyValidSpan( SyntaxNode root, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken) { // return statement shouldn't contain any return value if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null)) { return false; } var lastToken = root.FindToken(textSpan.End); if (lastToken.Kind() == SyntaxKind.None) { return false; } var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { return false; } var body = container.GetBlockBody(); if (body == null) { return false; } // make sure that next token of the last token in the selection is the close braces of containing block if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true)) { return false; } // alright, for these constructs, it must be okay to be extracted switch (container.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return true; } // now, only method is okay to be extracted out if (body.Parent is not MethodDeclarationSyntax method) { return false; } // make sure this method doesn't have return type. return method.ReturnType is PredefinedTypeSyntax p && p.Keyword.Kind() == SyntaxKind.VoidKeyword; } private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan) { // beginning of a file if (textSpan.IsEmpty || textSpan.End == 0) { return textSpan; } // if it is a start of new line, make it belong to previous line var line = text.Lines.GetLineFromPosition(textSpan.End); if (line.Start != textSpan.End) { return textSpan; } // get previous line Contract.ThrowIfFalse(line.LineNumber > 0); var previousLine = text.Lines[line.LineNumber - 1]; // if the span is past the end of the line (ie, in whitespace) then // return to the end of the line including whitespace if (textSpan.Start > previousLine.End) { return TextSpan.FromBounds(textSpan.Start, previousLine.EndIncludingLineBreak); } return TextSpan.FromBounds(textSpan.Start, previousLine.End); } private class SelectionInfo { public OperationStatus Status { get; set; } public TextSpan OriginalSpan { get; set; } public TextSpan FinalSpan { get; set; } public SyntaxNode CommonRootFromOriginalSpan { get; set; } public SyntaxToken FirstTokenInOriginalSpan { get; set; } public SyntaxToken LastTokenInOriginalSpan { get; set; } public SyntaxToken FirstTokenInFinalSpan { get; set; } public SyntaxToken LastTokenInFinalSpan { get; set; } public bool SelectionInExpression { get; set; } public bool SelectionInSingleStatement { get; set; } public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter) => With(s => s.Status = statusGetter(s.Status)); public SelectionInfo With(Action<SelectionInfo> valueSetter) { var newInfo = Clone(); valueSetter(newInfo); return newInfo; } public SelectionInfo Clone() => (SelectionInfo)MemberwiseClone(); } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/SymbolSpecification/SymbolSpecificationViewModel.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } private string _symbolSpecName; public bool CanBeDeleted { get; set; } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel( string languageName, bool canBeDeleted, INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { } public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService) { CanBeDeleted = canBeDeleted; _notificationService = notificationService; ItemName = specification.Name; ID = specification.ID; // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_CSharp_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_CSharp_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_CSharp_Struct, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_CSharp_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_CSharp_Enum, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_CSharp_Property, specification), new SymbolKindViewModel(MethodKind.Ordinary, ServicesVSResources.NamingSpecification_CSharp_Method, specification), new SymbolKindViewModel(MethodKind.LocalFunction, ServicesVSResources.NamingSpecification_CSharp_LocalFunction, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_CSharp_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_CSharp_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_CSharp_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_CSharp_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_CSharp_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_CSharp_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "private protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(SymbolKind.Namespace, ServicesVSResources.NamingSpecification_VisualBasic_Namespace, specification), new SymbolKindViewModel(TypeKind.Class, ServicesVSResources.NamingSpecification_VisualBasic_Class, specification), new SymbolKindViewModel(TypeKind.Struct, ServicesVSResources.NamingSpecification_VisualBasic_Structure, specification), new SymbolKindViewModel(TypeKind.Interface, ServicesVSResources.NamingSpecification_VisualBasic_Interface, specification), new SymbolKindViewModel(TypeKind.Enum, ServicesVSResources.NamingSpecification_VisualBasic_Enum, specification), new SymbolKindViewModel(TypeKind.Module, ServicesVSResources.NamingSpecification_VisualBasic_Module, specification), new SymbolKindViewModel(SymbolKind.Property, ServicesVSResources.NamingSpecification_VisualBasic_Property, specification), new SymbolKindViewModel(SymbolKind.Method, ServicesVSResources.NamingSpecification_VisualBasic_Method, specification), new SymbolKindViewModel(SymbolKind.Field, ServicesVSResources.NamingSpecification_VisualBasic_Field, specification), new SymbolKindViewModel(SymbolKind.Event, ServicesVSResources.NamingSpecification_VisualBasic_Event, specification), new SymbolKindViewModel(TypeKind.Delegate, ServicesVSResources.NamingSpecification_VisualBasic_Delegate, specification), new SymbolKindViewModel(SymbolKind.Parameter, ServicesVSResources.NamingSpecification_VisualBasic_Parameter, specification), new SymbolKindViewModel(SymbolKind.TypeParameter, ServicesVSResources.NamingSpecification_VisualBasic_TypeParameter, specification), new SymbolKindViewModel(SymbolKind.Local, ServicesVSResources.NamingSpecification_VisualBasic_Local, specification) }; // Not localized because they're language keywords AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), new AccessibilityViewModel(Accessibility.ProtectedAndInternal, "Private Protected", specification), new AccessibilityViewModel(Accessibility.NotApplicable, "Local", specification), }; // Not localized because they're language keywords ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } public string ItemName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, ItemName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolOrTypeOrMethodKind()).ToImmutableArray(), AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(), ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray()); } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } // For screen readers public override string ToString() => _symbolSpecName; internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private readonly MethodKind? _methodKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { _symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { _typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } public SymbolKindViewModel(MethodKind methodKind, string name, SymbolSpecification specification) { _methodKind = methodKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.MethodKind == methodKind); } internal SymbolKindOrTypeKind CreateSymbolOrTypeOrMethodKind() { return _symbolKind.HasValue ? new SymbolKindOrTypeKind(_symbolKind.Value) : _typeKind.HasValue ? new SymbolKindOrTypeKind(_typeKind.Value) : _methodKind.HasValue ? new SymbolKindOrTypeKind(_methodKind.Value) : throw ExceptionUtilities.Unreachable; } } public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility); } } public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { _modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Features/LanguageServer/ProtocolUnitTests/Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <StartupObject /> <TargetFramework>net472</TargetFramework> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.LanguageServer.UnitTests</RootNamespace> <RoslynProjectType>UnitTest</RoslynProjectType> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> </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 Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <StartupObject /> <TargetFramework>net472</TargetFramework> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.LanguageServer.UnitTests</RootNamespace> <RoslynProjectType>UnitTest</RoslynProjectType> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Core/Implementation/ITextUndoHistoryWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor { internal interface ITextUndoHistoryWorkspaceService : IWorkspaceService { bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor { internal interface ITextUndoHistoryWorkspaceService : IWorkspaceService { bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory); } }
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent Public Class GenerateEventCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a(x As Integer) Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>public interface i { event gooEventHandler goo; } public delegate void gooEventHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a as EventHandler Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>using System; public interface i { event EventHandler goo; }</text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> <WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")> Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c WithEvents field as Program Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public class Program { } </Document> </Project> </Workspace> Dim expected = <text>public class Program { public event EvHandler Ev; } public delegate void EvHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function #Disable Warning CA2243 ' Attribute string literals should parse correctly <WorkItem(144843, "Generate method stub generates into *.Designer.cs")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task #Enable Warning CA2243 ' Attribute string literals should parse correctly Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document> Class c WithEvents field as UserControl1 Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> <Document FilePath="UserControl1.Designer.vb"> ' This file is auto-generated Partial Class UserControl1 End Class </Document> <Document FilePath="UserControl1.vb"> Partial Public Class UserControl1 End Class </Document> </Project> </Workspace> Dim expectedFileWithText = New Dictionary(Of String, String) From { {"UserControl1.vb", <Text> Partial Public Class UserControl1 Public Event Ev(x As Integer) End Class </Text>.Value.Trim()}, {"UserControl1.Designer.vb", <Text> ' This file is auto-generated Partial Class UserControl1 End Class </Text>.Value.Trim()} } Await TestAsync(input, fileNameToExpected:=expectedFileWithText) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent Public Class GenerateEventCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a(x As Integer) Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>public interface i { event gooEventHandler goo; } public delegate void gooEventHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a as EventHandler Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>using System; public interface i { event EventHandler goo; }</text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> <WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")> Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c WithEvents field as Program Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public class Program { } </Document> </Project> </Workspace> Dim expected = <text>public class Program { public event EvHandler Ev; } public delegate void EvHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function #Disable Warning CA2243 ' Attribute string literals should parse correctly <WorkItem(144843, "Generate method stub generates into *.Designer.cs")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task #Enable Warning CA2243 ' Attribute string literals should parse correctly Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document> Class c WithEvents field as UserControl1 Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> <Document FilePath="UserControl1.Designer.vb"> ' This file is auto-generated Partial Class UserControl1 End Class </Document> <Document FilePath="UserControl1.vb"> Partial Public Class UserControl1 End Class </Document> </Project> </Workspace> Dim expectedFileWithText = New Dictionary(Of String, String) From { {"UserControl1.vb", <Text> Partial Public Class UserControl1 Public Event Ev(x As Integer) End Class </Text>.Value.Trim()}, {"UserControl1.Designer.vb", <Text> ' This file is auto-generated Partial Class UserControl1 End Class </Text>.Value.Trim()} } Await TestAsync(input, fileNameToExpected:=expectedFileWithText) End Function End Class End Namespace
-1
dotnet/roslyn
56,424
EnC/HR interface unification
Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
tmat
"2021-09-15T22:22:11Z"
"2021-09-21T16:03:37Z"
8574e338076f0a2d7a4bc0d129f00e7440e47fbb
240a47028f8518833271b026667f18f2c02fcbd8
EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up. Contributes to https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800 https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091 Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { /// <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> public static async Task<ImmutableArray<ISymbol>> FindImplementationsForInterfaceMemberAsync( this ITypeSymbol typeSymbol, ISymbol interfaceMember, Solution solution, CancellationToken cancellationToken) { // This method can return multiple results. Consider the case of: // // interface IGoo<X> { void Goo(X x); } // // class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); } // // If you're looking for the implementations of IGoo<X>.Goo then you want to find both // results in C. using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder); // TODO(cyrusn): Implement this using the actual code for // TypeSymbol.FindImplementationForInterfaceMember if (typeSymbol == null || interfaceMember == null) return ImmutableArray<ISymbol>.Empty; if (interfaceMember.Kind is not SymbolKind.Event and not SymbolKind.Method and not SymbolKind.Property) { return ImmutableArray<ISymbol>.Empty; } // WorkItem(4843) // // 'typeSymbol' has to at least implement the interface containing the member. note: // this just means that the interface shows up *somewhere* in the inheritance chain of // this type. However, this type may not actually say that it implements it. For // example: // // interface I { void Goo(); } // // class B { } // // class C : B, I { } // // class D : C { } // // D does implement I transitively through C. However, even if D has a "Goo" method, it // won't be an implementation of I.Goo. The implementation of I.Goo must be from a type // that actually has I in it's direct interface chain, or a type that's a base type of // that. in this case, that means only classes C or B. var interfaceType = interfaceMember.ContainingType; if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType)) return ImmutableArray<ISymbol>.Empty; // We've ascertained that the type T implements some constructed type of the form I<X>. // However, we're not precisely sure which constructions of I<X> are being used. For // example, a type C might implement I<int> and I<string>. If we're searching for a // method from I<X> we might need to find several methods that implement different // instantiations of that method. var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition; var originalInterfaceMember = interfaceMember.OriginalDefinition; var constructedInterfaces = typeSymbol.AllInterfaces.Where(i => SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType)); foreach (var constructedInterface in constructedInterfaces) { cancellationToken.ThrowIfCancellationRequested(); // OriginalSymbolMatch allows types to be matched across different assemblies if they are considered to // be the same type, which provides a more accurate implementations list for interfaces. var constructedInterfaceMember = await constructedInterface.GetMembers(interfaceMember.Name).FirstOrDefaultAsync( typeSymbol => SymbolFinder.OriginalSymbolsMatchAsync(solution, typeSymbol, interfaceMember, cancellationToken)).ConfigureAwait(false); if (constructedInterfaceMember == null) { continue; } // Now we need to walk the base type chain, but we start at the first type that actually // has the interface directly in its interface hierarchy. var seenTypeDeclaringInterface = false; for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType) { seenTypeDeclaringInterface = seenTypeDeclaringInterface || currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition); if (seenTypeDeclaringInterface) { var result = currentType.FindImplementations(constructedInterfaceMember, solution.Workspace); if (result != null) { builder.Add(result); break; } } } } return builder.ToImmutable(); } public static ISymbol? FindImplementations(this ITypeSymbol typeSymbol, ISymbol constructedInterfaceMember, Workspace workspace) => constructedInterfaceMember switch { IEventSymbol eventSymbol => typeSymbol.FindImplementations(eventSymbol, workspace), IMethodSymbol methodSymbol => typeSymbol.FindImplementations(methodSymbol, workspace), IPropertySymbol propertySymbol => typeSymbol.FindImplementations(propertySymbol, workspace), _ => null, }; private static ISymbol? FindImplementations<TSymbol>( this ITypeSymbol typeSymbol, TSymbol constructedInterfaceMember, Workspace workspace) where TSymbol : class, ISymbol { // Check the current type for explicit interface matches. Otherwise, check // the current type and base types for implicit matches. var explicitMatches = from member in typeSymbol.GetMembers().OfType<TSymbol>() from explicitInterfaceMethod in member.ExplicitInterfaceImplementations() where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, constructedInterfaceMember) select member; var provider = workspace.Services.GetLanguageServices(typeSymbol.Language); var semanticFacts = provider.GetRequiredService<ISemanticFactsService>(); // Even if a language only supports explicit interface implementation, we // can't enforce it for types from metadata. For example, a VB symbol // representing System.Xml.XmlReader will say it implements IDisposable, but // the XmlReader.Dispose() method will not be an explicit implementation of // IDisposable.Dispose() if ((!semanticFacts.SupportsImplicitInterfaceImplementation && typeSymbol.Locations.Any(location => location.IsInSource)) || typeSymbol.TypeKind == TypeKind.Interface) { return explicitMatches.FirstOrDefault(); } var syntaxFacts = provider.GetRequiredService<ISyntaxFactsService>(); var implicitMatches = from baseType in typeSymbol.GetBaseTypesAndThis() from member in baseType.GetMembers(constructedInterfaceMember.Name).OfType<TSymbol>() where member.DeclaredAccessibility == Accessibility.Public && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, constructedInterfaceMember, syntaxFacts.IsCaseSensitive) select member; return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault(); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, IEnumerable<ITypeParameterSymbol> availableTypeParameters) { return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet()); } [return: NotNullIfNotNull(parameterName: "type")] private static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, ISet<string> availableTypeParameterNames) { return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveAnonymousTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new AnonymousTypeRemover(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnnamedErrorTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new UnnamedErrorTypeRemover(compilation)); } public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true)); return result; } public static IList<ITypeParameterSymbol> GetReferencedTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false)); return result; } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, Compilation compilation) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, ITypeGenerator typeGenerator) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { /// <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> public static async Task<ImmutableArray<ISymbol>> FindImplementationsForInterfaceMemberAsync( this ITypeSymbol typeSymbol, ISymbol interfaceMember, Solution solution, CancellationToken cancellationToken) { // This method can return multiple results. Consider the case of: // // interface IGoo<X> { void Goo(X x); } // // class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); } // // If you're looking for the implementations of IGoo<X>.Goo then you want to find both // results in C. using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder); // TODO(cyrusn): Implement this using the actual code for // TypeSymbol.FindImplementationForInterfaceMember if (typeSymbol == null || interfaceMember == null) return ImmutableArray<ISymbol>.Empty; if (interfaceMember.Kind is not SymbolKind.Event and not SymbolKind.Method and not SymbolKind.Property) { return ImmutableArray<ISymbol>.Empty; } // WorkItem(4843) // // 'typeSymbol' has to at least implement the interface containing the member. note: // this just means that the interface shows up *somewhere* in the inheritance chain of // this type. However, this type may not actually say that it implements it. For // example: // // interface I { void Goo(); } // // class B { } // // class C : B, I { } // // class D : C { } // // D does implement I transitively through C. However, even if D has a "Goo" method, it // won't be an implementation of I.Goo. The implementation of I.Goo must be from a type // that actually has I in it's direct interface chain, or a type that's a base type of // that. in this case, that means only classes C or B. var interfaceType = interfaceMember.ContainingType; if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType)) return ImmutableArray<ISymbol>.Empty; // We've ascertained that the type T implements some constructed type of the form I<X>. // However, we're not precisely sure which constructions of I<X> are being used. For // example, a type C might implement I<int> and I<string>. If we're searching for a // method from I<X> we might need to find several methods that implement different // instantiations of that method. var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition; var originalInterfaceMember = interfaceMember.OriginalDefinition; var constructedInterfaces = typeSymbol.AllInterfaces.Where(i => SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType)); foreach (var constructedInterface in constructedInterfaces) { cancellationToken.ThrowIfCancellationRequested(); // OriginalSymbolMatch allows types to be matched across different assemblies if they are considered to // be the same type, which provides a more accurate implementations list for interfaces. var constructedInterfaceMember = await constructedInterface.GetMembers(interfaceMember.Name).FirstOrDefaultAsync( typeSymbol => SymbolFinder.OriginalSymbolsMatchAsync(solution, typeSymbol, interfaceMember, cancellationToken)).ConfigureAwait(false); if (constructedInterfaceMember == null) { continue; } // Now we need to walk the base type chain, but we start at the first type that actually // has the interface directly in its interface hierarchy. var seenTypeDeclaringInterface = false; for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType) { seenTypeDeclaringInterface = seenTypeDeclaringInterface || currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition); if (seenTypeDeclaringInterface) { var result = currentType.FindImplementations(constructedInterfaceMember, solution.Workspace); if (result != null) { builder.Add(result); break; } } } } return builder.ToImmutable(); } public static ISymbol? FindImplementations(this ITypeSymbol typeSymbol, ISymbol constructedInterfaceMember, Workspace workspace) => constructedInterfaceMember switch { IEventSymbol eventSymbol => typeSymbol.FindImplementations(eventSymbol, workspace), IMethodSymbol methodSymbol => typeSymbol.FindImplementations(methodSymbol, workspace), IPropertySymbol propertySymbol => typeSymbol.FindImplementations(propertySymbol, workspace), _ => null, }; private static ISymbol? FindImplementations<TSymbol>( this ITypeSymbol typeSymbol, TSymbol constructedInterfaceMember, Workspace workspace) where TSymbol : class, ISymbol { // Check the current type for explicit interface matches. Otherwise, check // the current type and base types for implicit matches. var explicitMatches = from member in typeSymbol.GetMembers().OfType<TSymbol>() from explicitInterfaceMethod in member.ExplicitInterfaceImplementations() where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, constructedInterfaceMember) select member; var provider = workspace.Services.GetLanguageServices(typeSymbol.Language); var semanticFacts = provider.GetRequiredService<ISemanticFactsService>(); // Even if a language only supports explicit interface implementation, we // can't enforce it for types from metadata. For example, a VB symbol // representing System.Xml.XmlReader will say it implements IDisposable, but // the XmlReader.Dispose() method will not be an explicit implementation of // IDisposable.Dispose() if ((!semanticFacts.SupportsImplicitInterfaceImplementation && typeSymbol.Locations.Any(location => location.IsInSource)) || typeSymbol.TypeKind == TypeKind.Interface) { return explicitMatches.FirstOrDefault(); } var syntaxFacts = provider.GetRequiredService<ISyntaxFactsService>(); var implicitMatches = from baseType in typeSymbol.GetBaseTypesAndThis() from member in baseType.GetMembers(constructedInterfaceMember.Name).OfType<TSymbol>() where member.DeclaredAccessibility == Accessibility.Public && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, constructedInterfaceMember, syntaxFacts.IsCaseSensitive) select member; return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault(); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, IEnumerable<ITypeParameterSymbol> availableTypeParameters) { return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet()); } [return: NotNullIfNotNull(parameterName: "type")] private static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, ISet<string> availableTypeParameterNames) { return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveAnonymousTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new AnonymousTypeRemover(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnnamedErrorTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new UnnamedErrorTypeRemover(compilation)); } public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true)); return result; } public static IList<ITypeParameterSymbol> GetReferencedTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false)); return result; } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, Compilation compilation) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, ITypeGenerator typeGenerator) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator)); } } }
-1